Clone an object or an array

Benoît Blanchon
2017-06-21 22:35:36 +02:00
parent d870be93ec
commit c50e78e6e0

@@ -401,35 +401,35 @@ Throwing<DynamicJsonBuffer> jsonBuffer;
See issue [#205](https://github.com/bblanchon/ArduinoJson/issues/205).
## Reuse JsonBuffer
:warning: **JsonBuffer are designed to be non reusable.**
:warning: **This is on purpose and this is actually here to help!**
:warning: **It prevents memory leaks and dangling pointer.**
:warning: **This section is only intended to insane people who deliberately ignores the recommendation of the library author.**
:warning: [READ THE FAQ BEFORE USING THIS!!!!!!!](https://bblanchon.github.io/ArduinoJson/faq/how-to-reuse-a-jsonbuffer/)
Here is how you can write your own `clear()` function:
## Clone an object or an array
```c++
template<typename T>
void clear(T& instance)
JsonVariant clone(JsonBuffer& jb, JsonVariant prototype)
{
instance = T();
if (prototype.is<JsonObject>()) {
const JsonObject& protoObj = prototype;
JsonObject& newObj = jb.createObject();
for (const auto& kvp : protoObj) {
newObj[kvp.key] = clone(jb, kvp.value);
}
return newObj;
}
if (prototype.is<JsonArray>()) {
const JsonArray& protoArr = prototype;
JsonArray& newArr = jb.createArray();
for (const auto& elem : protoArr) {
newArr.add(clone(jb, elem));
}
return newArr;
}
if (prototype.is<char*>()) {
return jb.strdup(prototype.as<char*>());
}
return prototype;
}
```
To use it in your code:
```c++
clear(jsonBuffer);
```
See issues [#72](https://github.com/bblanchon/ArduinoJson/issues/72), [#115](https://github.com/bblanchon/ArduinoJson/issues/115), [#141](https://github.com/bblanchon/ArduinoJson/issues/141)
See [ArduinoJson: Avoiding pitfalls](https://bblanchon.github.io/ArduinoJson/doc/pitfalls/#4-dont-reuse-the-same-jsonbuffer)
See issue [#533](https://github.com/bblanchon/ArduinoJson/issues/533)