From ffdc3986eae9e4bc86d8dbf7d65100a46f35bc68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Blanchon?= Date: Fri, 1 Apr 2016 11:06:08 +0200 Subject: [PATCH] Updated Bag of Tricks (markdown) --- Bag-of-Tricks.md | 64 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/Bag-of-Tricks.md b/Bag-of-Tricks.md index 4e0628f..753736e 100644 --- a/Bag-of-Tricks.md +++ b/Bag-of-Tricks.md @@ -24,6 +24,70 @@ for(int led : root["leds"].asArray()) { 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: Here is a proxy that will put bytes in a buffer before actually writing them to the destination: