From cbbf589a5eee280c7747112ea0419abb56e317ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Blanchon?= Date: Wed, 28 Oct 2015 16:06:53 +0100 Subject: [PATCH] Updated FAQ (markdown) --- FAQ.md | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/FAQ.md b/FAQ.md index 46a90fd..503b0ac 100644 --- a/FAQ.md +++ b/FAQ.md @@ -96,4 +96,42 @@ This will never be a part of the library. 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://github.com/bblanchon/ArduinoJson/wiki/Avoiding-pitfalls#4-dont-reuse-the-same-jsonbuffer) \ No newline at end of file +See [ArduinoJson: Avoiding pitfalls](https://github.com/bblanchon/ArduinoJson/wiki/Avoiding-pitfalls#4-dont-reuse-the-same-jsonbuffer) + +### What's the best way to use the library? + +Here is the canonical example for serializing and deserializing with ArduinoJson. + +By following this example, you are making the best usage of your memory and you maintain a good software design. + +```c++ +struct SensorData { + const char* name; + int time; + float value; +}; + +bool deserialize(SensorData& data, const char* json) +{ + StaticJsonBuffer<200> jsonBuffer; + JsonObject& root = jsonBuffer.parseObject(json) + data.name = json["name"]; + data.time = json["time"]; + data.value = json["value"]; + return root.success(); +} + +void serialize(const SensorData& data, char* json, size_t maxSize) +{ + StaticJsonBuffer<200> jsonBuffer; + JsonObject& root = jsonBuffer.createObject() + root["name"] = data.name; + root["time"] = data.time; + root["value"] = data.value; + root.printTo(json, maxSize); +} +``` + +As you can see the `StaticJsonBuffer` is kept in memory as short as possible, so that the remain of your program is unaffected by the JSON serialization. + +Also you can see that neither `JsonArray` nor `JsonObject` leak out of the serialization code. This maintain a good isolation and reduce the coupling with the library. \ No newline at end of file