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:

  1. Memory usage: a JsonVariant is much larger than an int, for example.
  2. Execution speed: accessing a member of a JsonDocument is much slower than accessing a struct member.
  3. Code size: accessing a member of a JsonDocument generates more instructions than accessing a struct member.

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

Global warming stripes by Professor Ed Hawkins (University of Reading)