From eb80d176f12133424ae0fda5ddc41062769af3cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Blanchon?= Date: Sun, 8 Nov 2015 10:09:47 +0100 Subject: [PATCH] Updated FAQ (markdown) --- FAQ.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/FAQ.md b/FAQ.md index ebb7304..fafa9d0 100644 --- a/FAQ.md +++ b/FAQ.md @@ -58,6 +58,55 @@ for (int i=0; i<10; i++) { Note that, contrary to a common belief, moving a `StaticJsonBuffer` inside of a loop has no negative impact on performance. +##### Cause 2: reuse of JSON input + +In order to make the JSON parsing without any allocation or duplication, ArduinoJson modifies the string in place: it inserts null terminators and unescapes special characters. + +If you provide a writeable input, like a `char[]` or a `char*`, it will modify this input in place. +If you provide a read only input, like a `const char*` or a `String`, it will have to make a copy of it in order to be allowed to modify it. + +That's why it's highly recommended to used a writeable input: you get a huge performance boost and memory usage is greatly reduced :+1: + +Now, this behavior leads to unexpected result if you try to reuse the modified string, for instance: + +```c++ +char json[256]; +readJsonFromSomewhere(json, sizeof(json)); + +for (int i=0; i<10; i++) { + StaticJsonBuffer<200> jsonBuffer; + + JsonObject& root = jsonBuffer.parse(json); + if (root.success()) { + Serial.println("parseObject() succeeded"); + } else { + Serial.println("parseObject() failed!"); + } +} +``` + +Only the first call to `parseObject()` will succeed because after that call, `json` will be altered and not be valid JSON anymore. + +The solution is simply to parse the input only once, or get a fresh input at each iteration: + +```c++ +for (int i=0; i<10; i++) { + char json[256]; + readJsonFromSomewhere(json, sizeof(json)); + + StaticJsonBuffer<200> jsonBuffer; + + JsonObject& root = jsonBuffer.parse(json); + if (root.success()) { + Serial.println("parseObject() succeeded"); + } else { + Serial.println("parseObject() failed!"); + } +} +``` + +See issue [#153](https://github.com/bblanchon/ArduinoJson/issues/153) + ### What are the differences between `StaticJsonBuffer` and `DynamicJsonBuffer`? | `StaticJsonBuffer` | `DynamicJsonBuffer`