Why should I create a separate config object?
Why can’t I use JsonDocument directly?
As JsonConfigExample.ino shows, it’s important to use custom structures to store the state of your application.
Many users are puzzled by this advice. Why should I create my own structure when JsonDocument already contains all I need? Indeed, this seems like a perfect solution: the comfort of a loosely typed JavaScript object model inside a C++ program. Unfortunately, this solution is far from perfect; let’s see why in detail.
Reason 1: overhead
Passing through the JSON object model is less efficient regarding:
- Memory usage: a
JsonVariantis much larger than anint, for example. - Execution speed: accessing a member of a
JsonDocumentis much slower than accessing astructmember. - Code size: accessing a member of a
JsonDocumentgenerates more instructions than accessing astructmember.
Reason 2: type safety
Once your data is captured in C++ structures, you can rely on the security provided by the type system; you don’t have to check that such member is present and has the right type, which allows for detecting bugs at compile time.
Reason 3: coupling
The way information is serialized is an implementation detail; the rest of the program should not depend on it.
Moreover, you should not spread ArduinoJson everywhere in your code beacuse you would be too dependent on ArduinoJson. What if you want to use another library? What if I change the API again? You don’t want to be at the mercy of a library developer, even me.
See also
- JsonConfigExample.ino demonstrates this technique
- The case study “Configuration in SPIFFS” in Mastering ArduinoJson does the same with a complex configuration with nested objects.