JsonParserExample.ino 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. //
  7. // https://arduinojson.org/v6/example/parser/
  8. #include <ArduinoJson.h>
  9. void setup() {
  10. // Initialize serial port
  11. Serial.begin(9600);
  12. while (!Serial) continue;
  13. // Allocate the JSON document
  14. //
  15. // Inside the brackets, 200 is the capacity of the memory pool in bytes.
  16. // Don't forget to change this value to match your JSON document.
  17. // Use arduinojson.org/v6/assistant to compute the capacity.
  18. StaticJsonDocument<200> doc;
  19. // StaticJsonDocument<N> allocates memory on the stack, it can be
  20. // replaced by DynamicJsonDocument which allocates in the heap.
  21. //
  22. // DynamicJsonDocument doc(200);
  23. // JSON input string.
  24. //
  25. // Using a char[], as shown here, enables the "zero-copy" mode. This mode uses
  26. // the minimal amount of memory because the JsonDocument stores pointers to
  27. // the input buffer.
  28. // If you use another type of input, ArduinoJson must copy the strings from
  29. // the input to the JsonDocument, so you need to increase the capacity of the
  30. // JsonDocument.
  31. char json[] =
  32. "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
  33. // Deserialize the JSON document
  34. DeserializationError error = deserializeJson(doc, json);
  35. // Test if parsing succeeds.
  36. if (error) {
  37. Serial.print(F("deserializeJson() failed: "));
  38. Serial.println(error.c_str());
  39. return;
  40. }
  41. // Fetch values.
  42. //
  43. // Most of the time, you can rely on the implicit casts.
  44. // In other case, you can do doc["time"].as<long>();
  45. const char* sensor = doc["sensor"];
  46. long time = doc["time"];
  47. double latitude = doc["data"][0];
  48. double longitude = doc["data"][1];
  49. // Print values.
  50. Serial.println(sensor);
  51. Serial.println(time);
  52. Serial.println(latitude, 6);
  53. Serial.println(longitude, 6);
  54. }
  55. void loop() {
  56. // not used in this example
  57. }
  58. // See also
  59. // --------
  60. //
  61. // https://arduinojson.org/ contains the documentation for all the functions
  62. // used above. It also includes an FAQ that will help you solve any
  63. // deserialization problem.
  64. //
  65. // The book "Mastering ArduinoJson" contains a tutorial on deserialization.
  66. // It begins with a simple example, like the one above, and then adds more
  67. // features like deserializing directly from a file or an HTTP request.
  68. // Learn more at https://arduinojson.org/book/
  69. // Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤