Description

JsonDocument stores a JSON document in memory. It owns the memory referenced by JsonArray, JsonObject, and JsonVariant.

JsonDocument contains a fixed-size memory pool, with a monotonic allocator. This design allows ArduinoJson to be very efficient but requires some discipline on your side:

  1. Because the size is fixed, you need to specify the size when you create the JsonDocument
  2. Because the allocator is monotonic, it cannot release memory when you call JsonObject::remove() for example.

You can choose to store your JsonDocument in the stack or in the heap:

  • Use a StaticJsonDocument to store in the stack (recommended for documents smaller than 1KB)
  • Use a DynamicJsonDocument to store in the heap (recommended for documents larger than 1KB)

I strongly recommend against using a global JsonDocument because you would be troubled by the monotonic allocator, and would make an inefficient usage of your RAM.

On the contrary, I recommend declaring a short-lived JsonDocument that you use only in your serialization functions.

History

In older versions, DynamicJsonDocument was able to grow if needed. Starting with version 6.7.0, DynamicJsonDocument has a fixed capacity, just like StaticJsonDocument. This change allows better performance, smaller code, and no heap fragmentation.

Arduino 6.6.0 contained a full-blown allocator (i.e. non monotonic) and was able to compact the memory inside the JsonDocument. This feature was reverted in version 6.7.0 because the overhead was unacceptable.

Member functions

Example

Here is a program that deserializes a JSON document and stores it in the stack:

StaticJsonDocument<200> doc; // <- a little more than 200 bytes in the stack

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

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

Here is a program that serializes a JSON document stored in the heap:

DynamicJsonDocument doc(200); // <- a little more than 200 bytes in the heap

JsonObject object = doc.to<JsonObject>();
object["hello"] = "world";

serializeJson(object, Serial);

See also