JsonGeneratorExample.ino 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright Benoit Blanchon 2014-2017
  2. // MIT License
  3. //
  4. // Arduino JSON library
  5. // https://bblanchon.github.io/ArduinoJson/
  6. // If you like this project, please add a star!
  7. #include <ArduinoJson.h>
  8. void setup() {
  9. Serial.begin(9600);
  10. while (!Serial) {
  11. // wait serial port initialization
  12. }
  13. // Memory pool for JSON object tree.
  14. //
  15. // Inside the brackets, 200 is the size of the pool in bytes.
  16. // If the JSON object is more complex, you need to increase that value.
  17. // See https://bblanchon.github.io/ArduinoJson/assistant/
  18. StaticJsonBuffer<200> jsonBuffer;
  19. // StaticJsonBuffer allocates memory on the stack, it can be
  20. // replaced by DynamicJsonBuffer which allocates in the heap.
  21. //
  22. // DynamicJsonBuffer jsonBuffer(200);
  23. // Create the root of the object tree.
  24. //
  25. // It's a reference to the JsonObject, the actual bytes are inside the
  26. // JsonBuffer with all the other nodes of the object tree.
  27. // Memory is freed when jsonBuffer goes out of scope.
  28. JsonObject& root = jsonBuffer.createObject();
  29. // Add values in the object
  30. //
  31. // Most of the time, you can rely on the implicit casts.
  32. // In other case, you can do root.set<long>("time", 1351824120);
  33. root["sensor"] = "gps";
  34. root["time"] = 1351824120;
  35. // Add a nested array.
  36. //
  37. // It's also possible to create the array separately and add it to the
  38. // JsonObject but it's less efficient.
  39. JsonArray& data = root.createNestedArray("data");
  40. data.add(48.756080);
  41. data.add(2.302038);
  42. root.printTo(Serial);
  43. // This prints:
  44. // {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}
  45. Serial.println();
  46. root.prettyPrintTo(Serial);
  47. // This prints:
  48. // {
  49. // "sensor": "gps",
  50. // "time": 1351824120,
  51. // "data": [
  52. // 48.756080,
  53. // 2.302038
  54. // ]
  55. // }
  56. }
  57. void loop() {
  58. // not used in this example
  59. }