DynamicJsonDocument
Description
DynamicJsonDocument is a JsonDocument that allocates its memory pool in the heap.
Because it calls malloc() and free(), DynamicJsonDocument is slightly slower than StaticJsonDocument.
DynamicJsonDocument allows storing much larger documents than StaticJsonDocument because it is not limited by the size of the stack.
Custom allocator
DynamicJsonDocument uses a default memory allocator that calls malloc() and free(). You can use other functions by passing a custom allocator class to BasicJsonDocument<T>. As an example, here is how DynamicJsonDocument is defined:
struct DefaultAllocator {
void* allocate(size_t n) {
return malloc(n);
}
void deallocate(void* p) {
free(p);
}
};
typedef BasicJsonDocument<DefaultAllocator> DynamicJsonDocument;
See BasicJsonDocument<T> for more information.
Member functions
as<T>()casts the root to the specified type (e.g.JsonArrayorJsonObject)add()adds elements to the root arraycapacity()returns the capacity of the memory poolclear()empties the document and resets the memory poolcontainsKey()tests if the root object contains the specified keycreateNestedArray()creates a nested array attached to the rootcreateNestedObject()create a nested object attached to the rootgarbageCollect()reclaims leaked memory blocksoperator[]gets or sets values in the documentoverflowed()tells if the memory pool was large enoughis<T>()tests the type of the rootisNull()tells if the document is null or emptymemoryUsage()tells how many bytes are used in the memory poolnesting()returns the number of nesting layers in the documentremove()removes an element (or member) at the specified index (or key)set()replaces the root with the specified valueshrinkToFit()reduces the capacity of the memory pool to match the current usage*size()returns the number of elements (or members) that the root array (or object) containsto<T>()clears the document and converts it to the specified type (e.g.JsonArrayorJsonObject)
Example
Here is a program that deserializes a JSON document using a DynamicJsonDocument:
DynamicJsonDocument doc(2048);
char json[] = "{\"hello\":\"world\"}";
deserializeJson(doc, json);
const char* world = doc["hello"];
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.