JsonParserExample.ino 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2024, Benoit BLANCHON
  3. // MIT License
  4. //
  5. // This example shows how to deserialize a JSON document with ArduinoJson.
  6. //
  7. // https://arduinojson.org/v7/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. JsonDocument doc;
  16. // JSON input string.
  17. const char* json =
  18. "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
  19. // Deserialize the JSON document
  20. DeserializationError error = deserializeJson(doc, json);
  21. // Test if parsing succeeds
  22. if (error) {
  23. Serial.print(F("deserializeJson() failed: "));
  24. Serial.println(error.f_str());
  25. return;
  26. }
  27. // Fetch the values
  28. //
  29. // Most of the time, you can rely on the implicit casts.
  30. // In other case, you can do doc["time"].as<long>();
  31. const char* sensor = doc["sensor"];
  32. long time = doc["time"];
  33. double latitude = doc["data"][0];
  34. double longitude = doc["data"][1];
  35. // Print the values
  36. Serial.println(sensor);
  37. Serial.println(time);
  38. Serial.println(latitude, 6);
  39. Serial.println(longitude, 6);
  40. }
  41. void loop() {
  42. // not used in this example
  43. }
  44. // See also
  45. // --------
  46. //
  47. // https://arduinojson.org/ contains the documentation for all the functions
  48. // used above. It also includes an FAQ that will help you solve any
  49. // deserialization problem.
  50. //
  51. // The book "Mastering ArduinoJson" contains a tutorial on deserialization.
  52. // It begins with a simple example, like the one above, and then adds more
  53. // features like deserializing directly from a file or an HTTP request.
  54. // Learn more at https://arduinojson.org/book/
  55. // Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤