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 modify 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.

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