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 just a 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.

Computing the size

The macro JSON_OBJECT_SIZE(n) returns the number of bytes required to store a JSON object that contains n key-value pairs. Use this macro to calculate the capacity of the JsonDocument.

This value only includes the size of the data structures that represent the object; if you have nested objects or strings, you need to add their sizes as well. You can use the ArduinoJson Assistant to generate the complete expression.

Example

Create an object and serialize it

// allocate the memory for the document
const size_t CAPACITY = JSON_OBJECT_SIZE(1);
StaticJsonDocument<CAPACITY> 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

// allocate the memory for the document
const size_t CAPACITY = JSON_OBJECT_SIZE(1);
StaticJsonDocument<CAPACITY> doc;

// deserialize the object
char json[] = "{\"hello\":\"world\"}";
deserializeJson(doc, json);

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

Member functions

See also