Description

A JSON array is an ordered collection of values. A JsonArray is a reference to this array, but a JsonDocument owns the data.

Because the JsonArray is a just reference, you need a JsonDocument to create a JSON object.

Computing the size

The macro JSON_ARRAY_SIZE(n) returns the number of bytes required to store a JSON array that contains n values. Use this macro to calculate the capacity of the JsonDocument.

This value only includes the size of the data structures that represent the array; 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 array and serialize it

// compute the required size
const size_t CAPACITY = JSON_ARRAY_SIZE(3);

// allocate the memory for the document
StaticJsonDocument<CAPACITY> doc;

// create an empty array
JsonArray array = doc.to<JsonArray>();
array.add(1);
array.add(2);
array.add(3);

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

Deserialize an array

// compute the required size
const size_t CAPACITY = JSON_ARRAY_SIZE(3);

// allocate the memory for the document
StaticJsonDocument<CAPACITY> doc;

// parse a JSON array
char json[] = "[1,2,3]";
deserializeJson(doc, json);

// extract the values
JsonArray array = doc.as<JsonArray>();
for(JsonVariant v : array) {
    Serial.println(v.as<int>());
}

Member functions

See also