JsonObject
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 just reference, you need a JsonDocument
to create an object. See the example below.
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"];