Description

A JSON object is a collection of key-value pair. 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 a JSON object. See the example below.

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