BasicJsonDocument<T>::shrinkToFit() reduces the capacity of the memory pool to match the current usage. Use this function to release some memory.
There is no reverse operation to resize the memory pool; you can only shrink it.
This function was added in ArduinoJson 6.14.0
Here is how you can deserialize using as much memory as possible, and then release what’s unused.
Example for ESP8266:
DynamicJsonDocument doc(ESP.getMaxFreeBlockSize()); deserializeJson(doc, json); doc.shrinkToFit();
Example for ESP32:
DynamicJsonDocument doc(ESP.getMaxAllocHeap()); deserializeJson(doc, json); doc.shrinkToFit();
In both examples, we call a function that returns the size of the largest block of free memory. The result may be significantly lower than the total available memory (
ESP.getFreeHeap()) if the heap is fragmented.
When the deserialization is complete, we call
shrinkToFit() to release all unused memory.