JsonParserExample.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. #include <iostream>
  7. #include "ArduinoJson.h"
  8. int main() {
  9. // Allocate the JSON document
  10. //
  11. // Inside the parentheses, 200 is the capacity of the memory pool in bytes.
  12. // Don't forget to change this value to match your JSON document.
  13. // Use https://arduinojson.org/v6/assistant to compute the capacity.
  14. JsonDocument doc(300);
  15. // JSON input string.
  16. //
  17. // Using a char[], as shown here, enables the "zero-copy" mode. This mode uses
  18. // the minimal amount of memory because the JsonDocument stores pointers to
  19. // the input buffer.
  20. // If you use another type of input, ArduinoJson must copy the strings from
  21. // the input to the JsonDocument, so you need to increase the capacity of the
  22. // JsonDocument.
  23. char json[] =
  24. "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
  25. // Deserialize the JSON document
  26. DeserializationError error = deserializeJson(doc, json);
  27. // Test if parsing succeeds.
  28. if (error) {
  29. std::cerr << "deserializeJson() failed: " << error.c_str() << std::endl;
  30. return 1;
  31. }
  32. // Fetch values.
  33. //
  34. // Most of the time, you can rely on the implicit casts.
  35. // In other case, you can do doc["time"].as<long>();
  36. const char* sensor = doc["sensor"];
  37. long time = doc["time"];
  38. double latitude = doc["data"][0];
  39. double longitude = doc["data"][1];
  40. // Print values.
  41. std::cout << sensor << std::endl;
  42. std::cout << time << std::endl;
  43. std::cout << latitude << std::endl;
  44. std::cout << longitude << std::endl;
  45. return 0;
  46. }