JsonGeneratorExample.ino 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 <ArduinoJson.h>
  7. void setup() {
  8. // Initialize Serial port
  9. Serial.begin(9600);
  10. while (!Serial) continue;
  11. // Memory pool for JSON object tree.
  12. //
  13. // Inside the brackets, 200 is the size of the 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. StaticJsonBuffer<200> jsonBuffer;
  17. // StaticJsonBuffer allocates memory on the stack, it can be
  18. // replaced by DynamicJsonBuffer which allocates in the heap.
  19. //
  20. // DynamicJsonBuffer jsonBuffer(200);
  21. // Create the root of the object tree.
  22. //
  23. // It's a reference to the JsonObject, the actual bytes are inside the
  24. // JsonBuffer with all the other nodes of the object tree.
  25. // Memory is freed when jsonBuffer goes out of scope.
  26. JsonObject& root = jsonBuffer.createObject();
  27. // Add values in the object
  28. //
  29. // Most of the time, you can rely on the implicit casts.
  30. // In other case, you can do root.set<long>("time", 1351824120);
  31. root["sensor"] = "gps";
  32. root["time"] = 1351824120;
  33. // Add a nested array.
  34. //
  35. // It's also possible to create the array separately and add it to the
  36. // JsonObject but it's less efficient.
  37. JsonArray& data = root.createNestedArray("data");
  38. data.add(48.756080);
  39. data.add(2.302038);
  40. root.printTo(Serial);
  41. // This prints:
  42. // {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}
  43. Serial.println();
  44. root.prettyPrintTo(Serial);
  45. // This prints:
  46. // {
  47. // "sensor": "gps",
  48. // "time": 1351824120,
  49. // "data": [
  50. // 48.756080,
  51. // 2.302038
  52. // ]
  53. // }
  54. }
  55. void loop() {
  56. // not used in this example
  57. }
  58. // See also
  59. // --------
  60. //
  61. // https://arduinojson.org/ contains the documentation for all the functions
  62. // used above. It also includes an FAQ that will help you solve any
  63. // serialization problem.
  64. //
  65. // The book "Mastering ArduinoJson" contains a tutorial on serialization.
  66. // It begins with a simple example, like the one above, and then adds more
  67. // features like serializing directly to a file or an HTTP request.
  68. // Learn more at https://arduinojson.org/book/
  69. // Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤