JsonParserExample.ino 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2019
  3. // MIT License
  4. //
  5. // This example shows how to deserialize a JSON document with ArduinoJson.
  6. #include <ArduinoJson.h>
  7. void setup() {
  8. // Initialize serial port
  9. Serial.begin(9600);
  10. while (!Serial) continue;
  11. // Memory pool for JSON object tree.
  12. //
  13. // Inside the brackets, 200 is the size of the pool in bytes.
  14. // Don't forget to change this value to match your JSON document.
  15. // Use arduinojson.org/assistant to compute the capacity.
  16. StaticJsonBuffer<200> jsonBuffer;
  17. // StaticJsonBuffer allocates memory on the stack, it can be
  18. // replaced by DynamicJsonBuffer which allocates in the heap.
  19. //
  20. // DynamicJsonBuffer jsonBuffer(200);
  21. // JSON input string.
  22. //
  23. // It's better to use a char[] as shown here.
  24. // If you use a const char* or a String, ArduinoJson will
  25. // have to make a copy of the input in the JsonBuffer.
  26. char json[] =
  27. "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
  28. // Root of the object tree.
  29. //
  30. // It's a reference to the JsonObject, the actual bytes are inside the
  31. // JsonBuffer with all the other nodes of the object tree.
  32. // Memory is freed when jsonBuffer goes out of scope.
  33. JsonObject& root = jsonBuffer.parseObject(json);
  34. // Test if parsing succeeds.
  35. if (!root.success()) {
  36. Serial.println("parseObject() failed");
  37. return;
  38. }
  39. // Fetch values.
  40. //
  41. // Most of the time, you can rely on the implicit casts.
  42. // In other case, you can do root["time"].as<long>();
  43. const char* sensor = root["sensor"];
  44. long time = root["time"];
  45. double latitude = root["data"][0];
  46. double longitude = root["data"][1];
  47. // Print values.
  48. Serial.println(sensor);
  49. Serial.println(time);
  50. Serial.println(latitude, 6);
  51. Serial.println(longitude, 6);
  52. }
  53. void loop() {
  54. // not used in this example
  55. }
  56. // See also
  57. // --------
  58. //
  59. // https://arduinojson.org/ contains the documentation for all the functions
  60. // used above. It also includes an FAQ that will help you solve any
  61. // deserialization problem.
  62. //
  63. // The book "Mastering ArduinoJson" contains a tutorial on deserialization.
  64. // It begins with a simple example, like the one above, and then adds more
  65. // features like deserializing directly from a file or an HTTP request.
  66. // Learn more at https://arduinojson.org/book/
  67. // Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤