JsonParserExample.ino 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. // Allocate the JSON document
  12. //
  13. // Inside the brackets, 200 is the capacity of the memory pool in bytes.
  14. // Don't forget to change this value to match your JSON document.
  15. // Use arduinojson.org/v6/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. // Using a char[], as shown here, enables the "zero-copy" mode. This mode uses
  24. // the minimal amount of memory because the JsonDocument stores pointers to
  25. // the input buffer.
  26. // If you use another type of input, ArduinoJson must copy the strings from
  27. // the input to the JsonDocument, so you need to increase the capacity of the
  28. // JsonDocument.
  29. char json[] =
  30. "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
  31. // Deserialize the JSON document
  32. DeserializationError error = deserializeJson(doc, json);
  33. // Test if parsing succeeds.
  34. if (error) {
  35. Serial.print(F("deserializeJson() failed: "));
  36. Serial.println(error.c_str());
  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 doc["time"].as<long>();
  43. const char* sensor = doc["sensor"];
  44. long time = doc["time"];
  45. double latitude = doc["data"][0];
  46. double longitude = doc["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. // Visit https://arduinojson.org/v6/example/parser/ for more.