JsonGeneratorExample.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2020
  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. // Allocate 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/v6/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. // StaticJsonObject allocates memory on the stack, it can be
  20. // replaced by DynamicJsonDocument which allocates in the heap.
  21. //
  22. // DynamicJsonDocument doc(200);
  23. // Add values in the document
  24. //
  25. doc["sensor"] = "gps";
  26. doc["time"] = 1351824120;
  27. // Add an array.
  28. //
  29. JsonArray data = doc.createNestedArray("data");
  30. data.add(48.756080);
  31. data.add(2.302038);
  32. // Generate the minified JSON and send it to STDOUT
  33. //
  34. serializeJson(doc, std::cout);
  35. // The above line prints:
  36. // {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}
  37. // Start a new line
  38. std::cout << std::endl;
  39. // Generate the prettified JSON and send it to STDOUT
  40. //
  41. serializeJsonPretty(doc, std::cout);
  42. // The above line prints:
  43. // {
  44. // "sensor": "gps",
  45. // "time": 1351824120,
  46. // "data": [
  47. // 48.756080,
  48. // 2.302038
  49. // ]
  50. // }
  51. }