mirror of
https://github.com/bblanchon/ArduinoJson.git
synced 2025-09-25 22:40:56 +02:00
Updated Bag of Tricks (markdown)
@@ -24,6 +24,70 @@ for(int led : root["leds"].asArray()) {
|
|||||||
|
|
||||||
See issue [#246](https://github.com/bblanchon/ArduinoJson/issues/246)
|
See issue [#246](https://github.com/bblanchon/ArduinoJson/issues/246)
|
||||||
|
|
||||||
|
## Nested array in a nested array
|
||||||
|
|
||||||
|
Imagine you need to generate the following JSON:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"value1": "x",
|
||||||
|
"value2": [
|
||||||
|
[
|
||||||
|
"Yes",
|
||||||
|
"No"
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Maybe"
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The canonical way to do this is:
|
||||||
|
|
||||||
|
```c++
|
||||||
|
JsonObject& root = jsonBuffer.createObject();
|
||||||
|
|
||||||
|
root["value1"] = "x";
|
||||||
|
JsonArray& value2 = root.createNestedArray("value2");
|
||||||
|
|
||||||
|
JsonArray& yesno = value2.createNestedArray();
|
||||||
|
yesno.add("Yes");
|
||||||
|
yesno.add("No");
|
||||||
|
|
||||||
|
JsonArray& maybe = value2.createNestedArray();
|
||||||
|
maybe.add("Maybe");
|
||||||
|
```
|
||||||
|
|
||||||
|
It's also possible to create the arrays and then put them in the object:
|
||||||
|
|
||||||
|
```c++
|
||||||
|
JsonObject& root = jsonBuffer.createObject();
|
||||||
|
JsonObject& value2 = jsonBuffer.createArray();
|
||||||
|
JsonObject& yesno = jsonBuffer.createArray();
|
||||||
|
JsonObject& maybe = jsonBuffer.createArray();
|
||||||
|
|
||||||
|
root["value1"] = "x";
|
||||||
|
root["value2"] = value2;
|
||||||
|
value2.add(yesno);
|
||||||
|
yesno.add("Yes");
|
||||||
|
yesno.add("No");
|
||||||
|
value2.add(maybe);
|
||||||
|
maybe.add("Maybe");
|
||||||
|
```
|
||||||
|
|
||||||
|
But it's a little less efficient in term of CPU and memory.
|
||||||
|
|
||||||
|
Lastly, it's possible to manually encode the nested array with an undocumented feature:
|
||||||
|
|
||||||
|
```c++
|
||||||
|
JsonObject& root = jsonBuffer.createObject();
|
||||||
|
root["value1"] = "x";
|
||||||
|
root["value2"] = ArduinoJson::Internals::Unparsed("[[\"Yes\",\"No\"],[\"Maybe\"]");
|
||||||
|
```
|
||||||
|
|
||||||
|
See issue [#252](https://github.com/bblanchon/ArduinoJson/issues/252)
|
||||||
|
|
||||||
## Buffered output:
|
## Buffered output:
|
||||||
|
|
||||||
Here is a proxy that will put bytes in a buffer before actually writing them to the destination:
|
Here is a proxy that will put bytes in a buffer before actually writing them to the destination:
|
||||||
|
Reference in New Issue
Block a user