mirror of
https://github.com/bblanchon/ArduinoJson.git
synced 2025-08-17 19:41:16 +02:00
Updated FAQ (markdown)
49
FAQ.md
49
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`
|
||||
|
Reference in New Issue
Block a user