JsonGeneratorExample.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2019
  3. // MIT License
  4. //
  5. // This example shows how to generate a JSON document with ArduinoJson.
  6. #include <iostream>
  7. #include "ArduinoJson.h"
  8. int main() {
  9. // The JSON document
  10. //
  11. // Inside the brackets, 200 is the RAM allocated to this document.
  12. // Don't forget to change this value to match your requirement.
  13. // Use arduinojson.org/assistant to compute the capacity.
  14. StaticJsonDocument<200> doc;
  15. // StaticJsonObject allocates memory on the stack, it can be
  16. // replaced by DynamicJsonDocument which allocates in the heap.
  17. //
  18. // DynamicJsonDocument doc(200);
  19. // Make our document be an object
  20. JsonObject root = doc.to<JsonObject>();
  21. // Add values in the object
  22. //
  23. // Most of the time, you can rely on the implicit casts.
  24. // In other case, you can do root.set<long>("time", 1351824120);
  25. root["sensor"] = "gps";
  26. root["time"] = 1351824120;
  27. // Add an array.
  28. //
  29. JsonArray data = root.createNestedArray("data");
  30. data.add(48.756080);
  31. data.add(2.302038);
  32. serializeJson(root, std::cout);
  33. // This prints:
  34. // {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}
  35. std::cout << std::endl;
  36. serializeJsonPretty(root, std::cout);
  37. // This prints:
  38. // {
  39. // "sensor": "gps",
  40. // "time": 1351824120,
  41. // "data": [
  42. // 48.756080,
  43. // 2.302038
  44. // ]
  45. // }
  46. return 0;
  47. }