JsonParserExample.cpp 1.8 KB

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