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