JsonParserExample.ino 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2023, Benoit BLANCHON
  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)
  13. continue;
  14. // Allocate the JSON document
  15. //
  16. // Inside the parentheses, 200 is the capacity of the memory pool in bytes.
  17. // Don't forget to change this value to match your JSON document.
  18. // Use https://arduinojson.org/v6/assistant to compute the capacity.
  19. JsonDocument doc(200);
  20. // JSON input string.
  21. //
  22. // Using a char[], as shown here, enables the "zero-copy" mode. This mode uses
  23. // the minimal amount of memory because the JsonDocument stores pointers to
  24. // the input buffer.
  25. // If you use another type of input, ArduinoJson must copy the strings from
  26. // the input to the JsonDocument, so you need to increase the capacity of the
  27. // JsonDocument.
  28. char json[] =
  29. "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
  30. // Deserialize the JSON document
  31. DeserializationError error = deserializeJson(doc, json);
  32. // Test if parsing succeeds.
  33. if (error) {
  34. Serial.print(F("deserializeJson() failed: "));
  35. Serial.println(error.f_str());
  36. return;
  37. }
  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 = doc["sensor"];
  43. long time = doc["time"];
  44. double latitude = doc["data"][0];
  45. double longitude = doc["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. // https://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. //
  62. // The book "Mastering ArduinoJson" contains a tutorial on deserialization.
  63. // It begins with a simple example, like the one above, and then adds more
  64. // features like deserializing directly from a file or an HTTP request.
  65. // Learn more at https://arduinojson.org/book/
  66. // Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤