[Arduino] JSON library 2.0
Hey! I’ve just released Arduino JSON library 2.0
In case you don’t know it already, it’s a free JSON library for embedded systems with the following features:
- Elegant API, very easy to use
- Fixed memory allocation (no malloc)
- Small footprint
EDIT: you should directly jump to version 5.0
What’s new in 2.0?
The only new feature in 2.0 is the JSON encoding.
There is a new API for the JSON encoding that has been designed with the same ingredients that made the success of the first one.
Here is a taste:
JsonArray<2> array;
array.add<6>(48.756080);
array.add<6>(2.302038);
JsonHashTable<3> root;
root.add("sensor", "gps");
root.add("time", 1351824120);
root.add("data", array);
Serial.print(root);
// {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}
The syntax is very close to the JSON parser, but the classes are not the same, they are in different namespaces.
New namespaces
The library is now divided into two parts:
- the JSON parser, within the namespace
ArduinoJson::Parser
- the JSON generator, within the namespace
ArduinoJson::Generator
This is a breaking change: you need to insert the following line in order to compile code written for version 1.
using namespace ArduinoJson::Parser;
People usually put the using
statements at the top of the file, but be careful, if you include both namespaces in the same file, type names JsonArray
and JsonHashTable
will collide.
Alternatively, you can put the using
statements inside a function body. For instance, you can use ArduinoJson::Parser
in one function and ArduinoJson::Generator
in another. In my opinion, this is the best solution.
If it’s not possible for you to do so, you can still prefix the type names with the namespace. For instance:
using namespace ArduinoJson;
Generator::JsonArray<2> generatorArray;
Parser::JsonArray parserArray;
Very small footprint
As for the JSON parser, I made a huge effort on reducing the size of the code and the size of the structures.
With Arduino JSON library, you only pay (in term of code size) for the features that you use in your application. The library is designed so that the GCC linker automatically removes the functions that you don’t use.
As an example, I compared the code size of Arduino JSON library with its biggest competitor: aJson . The test cases were two very simple (but realistic) programs:
- one that parses
{"sensor":"outdoor","value":25.6}
(source files are here) - another that generates this string (Source files are here)
The results are quite spectacular:
- the JSON parser is twice smaller than aJson
- the JSON generator is 7 times smaller than aJson