JsonParserExample.ino 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. // Allocate the JSON document
  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 DynamicJsonDocument which allocates in the heap.
  19. //
  20. // DynamicJsonDocument 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 root["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. // Visit https://arduinojson.org/v6/example/parser/ for more.