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 memory as found in the WROVER module. 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*);
};

allocate() has a signature similar to malloc(): it takes one parameter that specifies the size and returns a void*.

deallocate() has a signature similar to free(): it takes a void* that points to the buffer to release.

Member functions

Examples

DynamicJsonBuffer

As as 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;

External SPI 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.

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);
  }
};

using SpiRamJsonDocument = BasicJsonDocument<SpiRamAllocator>;

See also