JsonParserExample.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2018
  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. // Root JSON object
  10. //
  11. // Inside the brackets, 300 is the size of the memory pool in bytes.
  12. // Don't forget to change this value to match your JSON document.
  13. // Use arduinojson.org/assistant to compute the capacity.
  14. StaticJsonDocument<300> doc;
  15. // StaticJsonDocument<N> allocates memory on the stack, it can be
  16. // replaced by DynamicJsonObject which allocates in the heap.
  17. //
  18. // DynamicJsonObject doc(200);
  19. // JSON input string.
  20. //
  21. // It's better to use a char[] as shown here.
  22. // If you use a const char* or a String, ArduinoJson will
  23. // have to make a copy of the input in the JsonBuffer.
  24. char json[] =
  25. "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
  26. // Deserialize the JSON document
  27. DeserializationError error = deserializeJson(doc, json);
  28. // Test if parsing succeeds.
  29. if (error) {
  30. std::cerr << "deserializeJson() failed: " << error.c_str() << std::endl;
  31. return 1;
  32. }
  33. // Get the root object in the document
  34. JsonObject root = doc.as<JsonObject>();
  35. // Fetch values.
  36. //
  37. // Most of the time, you can rely on the implicit casts.
  38. // In other case, you can do doc["time"].as<long>();
  39. const char* sensor = root["sensor"];
  40. long time = root["time"];
  41. double latitude = root["data"][0];
  42. double longitude = root["data"][1];
  43. // Print values.
  44. std::cout << sensor << std::endl;
  45. std::cout << time << std::endl;
  46. std::cout << latitude << std::endl;
  47. std::cout << longitude << std::endl;
  48. return 0;
  49. }