JsonGeneratorExample.ino 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. // Root JSON object
  12. //
  13. // Inside the brackets, 200 is the size of the memory pool in bytes.
  14. // Don't forget to change this value to match your JSON document.
  15. // Use arduinojson.org/assistant to compute the capacity.
  16. StaticJsonObject<200> root;
  17. // StaticJsonObject allocates memory on the stack, it can be
  18. // replaced by DynamicJsonObject which allocates in the heap.
  19. //
  20. // DynamicJsonObject root(200);
  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 a nested array.
  28. //
  29. // It's also possible to create the array separately and add it to the
  30. // JsonObject but it's less efficient.
  31. JsonArray& data = root.createNestedArray("data");
  32. data.add(48.756080);
  33. data.add(2.302038);
  34. serializeJson(root, Serial);
  35. // This prints:
  36. // {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}
  37. Serial.println();
  38. serializeJsonPretty(root, 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. // See also
  53. // --------
  54. //
  55. // The website arduinojson.org contains the documentation for all the functions
  56. // used above. It also includes an FAQ that will help you solve any
  57. // serialization problem.
  58. // Please check it out at: https://arduinojson.org/
  59. //
  60. // The book "Mastering ArduinoJson" contains a tutorial on serialization.
  61. // It begins with a simple example, like the one above, and then adds more
  62. // features like serializing directly to a file or an HTTP request.
  63. // Please check it out at: https://arduinojson.org/book/