JsonGeneratorExample.ino 1.6 KB

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