Description

In ArduinoJson, an array is an ordered collection of values. A JsonArray is a reference to an array. The array itself resides in a JsonDocument.

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

Reference semantics

JsonArray points to an array in a JsonDocument, giving it reference semantics. Every modification you make through the JsonArray is reflected in the JsonDocument. When you copy a JsonArray, you only copy the reference, not the array itself.

Don’t pass a JsonArray by reference or pointer because it would be a reference to a reference, which is very confusing and can lead to dangling references if you reassign the JsonArray.

- void setCoordinates(JsonArray& coords) {
+ void setCoordinates(JsonArray coords) {
    JsonDocument doc;
    deserializeJson(doc, dataFile);
-   coords = doc["coordinates"];
+   coords.set(doc["coordinates"]);
  }

Avoid returning a JsonArray from a function, because it will likely point to a destructed JsonDocument. Consider returning a JsonDocument instead.

- JsonArray getCoordinates() {
+ JsonDocument getCoordinates() {
    JsonDocument doc;
    deserializeJson(doc, dataFile);
    return doc["coordinates"];
  }

Constness

You’ll see that most member functions of JsonArray are const. These methods do not modify the instance, but they may modify the array pointed by the JsonArray.

As we said, a JsonArray is a reference; the const-ness of the member functions refers to the reference object, not to the array.

ArduinoJson also supports a read-only reference type named JsonArrayConst. It’s similar to JsonArray, except it doesn’t allow modifying the array.

Example

Create an array and serialize it

// create an empty array
JsonDocument doc;
JsonArray array = doc.to<JsonArray>();

// add some values
array.add("hello");
array.add(42);
array.add(3.14);

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

Deserialize an array

JsonDocument doc;

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

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

Member functions

See also