The new version of ArduinoJson is out! It brings a few improvements concerning the duplication of strings.

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* are stored with a pointer, all other string types are duplicated, which greatly simplifies our programs.

String Storage const char* pointer char* pointer copy String copy const __FlashStringHelper* copy

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 );

Improvement 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:

String Storage RawJson(const char*) pointer RawJson(char*) copy RawJson(String) copy RawJson(const __FlashStringHelper*) copy

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.

How to get ArduinoJson 5.13.0?

You can download this new version from the Arduino Library Manager.

If you don’t use the Arduino IDE, you can download the single header version.