Description

In ArduinoJson, an object is a collection of key-value pairs. A JsonObject is a reference to this object, but a JsonDocument owns the data.

Because the JsonObject is a reference, you need a JsonDocument to create an object. See the example below.

Reference semantics

JsonObject points to an object in a JsonDocument, giving it reference semantics. Every modification you make through the JsonObject is reflected in the JsonDocument. When you copy a JsonObject, you only copy the reference, not the object itself.

Don’t pass a JsonObject by reference or pointer because it would be a reference to a reference, which is very confusing, and can lead to dangling references if you reassign the JsonObject.

- void setWifiConfig(JsonObject& cfg) {
+ void setWifiConfig(JsonObject cfg) {
    JsonDocument doc;
    deserializeJson(doc, configFile);
-   cfg = doc["wifi"];
+   cfg.set(doc["wifi"]);
  }

Avoid returning a JsonObject from a function, because it will likely point to a destructed JsonDocument. Consider returning a JsonDocument instead.

- JsonObject getWifiConfig() {
+ JsonDocument getWifiConfig() {
    JsonDocument doc;
    deserializeJson(doc, configFile);
    return doc["wifi"];
  }

Constness

You’ll see that most member functions of JsonObject are const. These methods do not modify the instance, but they may alter the object pointed by the JsonObject.

As we said, a JsonObject is a reference; the const-ness of the member functions refers to the reference class, not to the object.

ArduinoJson also supports a read-only reference type named JsonObjectConst. It’s similar to JsonObject, except it doesn’t allow modifying the object.

JsonObject vs JsonVariant

Both JsonObject and JsonVariant are references to values stored in the JsonDocument.

The difference is that JsonVariant can refer to any supported type (integer, float, string, array, object…), whereas JsonObject can only refer to an object. The advantage of JsonObject over JsonVariant is that it supports operations specific to objects, such as enumerating key-value pairs.

Example

Create an object and serialize it

JsonDocument doc;

// create an object
JsonObject object = doc.to<JsonObject>();
object["hello"] = "world";

// serialize the object and send the result to Serial
serializeJson(doc, Serial);

Deserialize an object

// deserialize the object
JsonDocument doc;
deserializeJson(doc, "{\"hello\":\"world\"}");

// extract the data
JsonObject object = doc.as<JsonObject>();
const char* world = object["hello"];

Member functions

See also

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