JsonParserExample.ino 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2018
  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. // Root JSON object
  12. //
  13. // Inside the brackets, 200 is the size of the memory 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. StaticJsonDocument<200> doc;
  17. // StaticJsonDocument<N> allocates memory on the stack, it can be
  18. // replaced by DynamicJsonObject which allocates in the heap.
  19. //
  20. // DynamicJsonObject doc(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. // Deserialize the JSON document
  29. DeserializationError error = deserializeJson(doc, json);
  30. // Test if parsing succeeds.
  31. if (error) {
  32. Serial.print(F("deserializeJson() failed: "));
  33. Serial.println(error.c_str());
  34. return;
  35. }
  36. // Get the root object in the document
  37. JsonObject& root = doc.as<JsonObject>();
  38. // Fetch values.
  39. //
  40. // Most of the time, you can rely on the implicit casts.
  41. // In other case, you can do doc["time"].as<long>();
  42. const char* sensor = root["sensor"];
  43. long time = root["time"];
  44. double latitude = root["data"][0];
  45. double longitude = root["data"][1];
  46. // Print values.
  47. Serial.println(sensor);
  48. Serial.println(time);
  49. Serial.println(latitude, 6);
  50. Serial.println(longitude, 6);
  51. }
  52. void loop() {
  53. // not used in this example
  54. }
  55. // See also
  56. // --------
  57. //
  58. // The website arduinojson.org contains the documentation for all the functions
  59. // used above. It also includes an FAQ that will help you solve any
  60. // deserialization problem.
  61. // Please check it out at: https://arduinojson.org/
  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. // Please check it out at: https://arduinojson.org/book/