I just released a new version of ArduinoJson, a library to serialize and deserialize JSON documents.
Let’s see what’s new.
New rules for string duplications
When a program adds a string, ArduinoJson stores it differently depending on the type of the string.
In previous versions, ArduinoJson stored a pointer when the string was a plain old C string (char*
, const char*
, char[]
), but stored a copy when the string had any other type (String
, Flash strings…).
ArduinoJson 5.13 changes the rules: now, only const char*
is stored with a pointer, all other string types are duplicated, which greatly simplifies our programs.
Example
Since older versions stored char[]
strings with a pointer, we used to see curious behavior when adding strings in a loop. To prevent ArduinoJson for storing the same pointer (an thus the same string) several times, we had to call JsonBuffer::strdup()
:
JsonArray& array = jsonBuffer.createArray();
for (int i=0; i<3; i++) {
char buffer[16];
sprintf(buffer, "iteration %d", 0);
array.add(jsonBuffer.strdup(buffer)); // <- need to duplicate :-(
}
array.printTo(Serial);
Thanks to the implicit duplication of char*
, we can simplify this program to:
JsonArray& array = jsonBuffer.createArray();
for (int i=0; i<3; i++) {
char buffer[16];
sprintf(buffer, "iteration %d", 0);
array.add(buffer); // <- implicit duplication :-)
}
array.printTo(Serial);
Improvements to RawJson()
RawJson()
is a special function to insert raw JSON fragments in a JsonArray
or a JsonObject
.
In previous versions, RawJson()
only accepted const char*
as an argument; now, in ArduinoJson 5.13, it also accepts String
objects and Flash strings too.
But there is more: strings marked with RawJson()
obey to the same duplication rules as other strings.
Here is an example:
JsonObject& root = jsonBuffer.createObject();
root["coord"] = RawJson(F("{\"lat\":48.74801,\"lon\":2.293491}"));
Bye bye strdup()
The new rules for string duplication make JsonBuffer::strdup()
useless.
In ArduinoJson 5.13, JsonBuffer::strdup()
is flagged as deprecated, so you’ll have a compilation warning if your program uses it.
I’ll probably remove the function in a future release, so I encourage you to update your programs.