BasicJsonDocument<T>
Description
BasicJsonDocument<T>
is the base class of DynamicJsonDocument
. It’s a JsonDocument
that allocates its memory pool using the allocator class T
.
Use this class when you want to use a custom memory allocator; for example, when you want to use an external PSRAM found in many ESP32 boards. See examples below.
This class was added in ArduinoJson 6.10.0
The allocator class
The allocator class must implement two member functions:
struct Allocator {
void* allocate(size_t);
void deallocate(void*);
void* reallocate(void*, size_t) ; // optional
};
allocate()
is similar to malloc()
deallocate()
is similar to free()
reallocate()
is similar to realloc()
. This member is optional and its only required if you call shrinkToFit()
.
Member functions
as<T>()
casts the root to the specified type (e.g.JsonArray
orJsonObject
)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.JsonArray
orJsonObject
)
Examples
DynamicJsonDocument
As as example here is how DynamicJsonDocument
is defined:
struct DefaultAllocator {
void* allocate(size_t size) {
return malloc(size);
}
void deallocate(void* ptr) {
free(ptr);
}
void* reallocate(void* ptr, size_t new_size) {
return realloc(ptr, new_size);
}
};
typedef BasicJsonDocument<DefaultAllocator> DynamicJsonDocument;
External RAM on ESP32
To use the external SPI memory on an ESP32, you must call heap_caps_malloc(MALLOC_CAP_SPIRAM)
instead of the usual malloc()
.
Such memory is available on the [WROVER module](WROVER Module
).
The following SpiRamJsonDocument
allocates its memory pool in the external RAM:
struct SpiRamAllocator {
void* allocate(size_t size) {
return heap_caps_malloc(size, MALLOC_CAP_SPIRAM);
}
void deallocate(void* pointer) {
heap_caps_free(pointer);
}
void* reallocate(void* ptr, size_t new_size) {
return heap_caps_realloc(ptr, new_size, MALLOC_CAP_SPIRAM);
}
};
using SpiRamJsonDocument = BasicJsonDocument<SpiRamAllocator>;
See: How to use external RAM on an ESP32?