8 #include <esp_heap_caps.h> 14 static const char *
const TAG =
"json";
16 static std::vector<char> global_json_build_buffer;
24 const size_t free_heap = ESP.getMaxFreeBlockSize();
25 #elif defined(USE_ESP32) 26 const size_t free_heap = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT);
29 size_t request_size = std::min(free_heap, (
size_t) 512);
31 ESP_LOGV(TAG,
"Attempting to allocate %u bytes for JSON serialization", request_size);
32 DynamicJsonDocument json_document(request_size);
33 if (json_document.capacity() == 0) {
35 "Could not allocate memory for JSON document! Requested %u bytes, largest free heap block: %u bytes",
36 request_size, free_heap);
39 JsonObject root = json_document.to<JsonObject>();
41 if (json_document.overflowed()) {
42 if (request_size == free_heap) {
43 ESP_LOGE(TAG,
"Could not allocate memory for JSON document! Overflowed largest free heap block: %u bytes",
47 request_size = std::min(request_size * 2, free_heap);
50 json_document.shrinkToFit();
51 ESP_LOGV(TAG,
"Size after shrink %u bytes", json_document.capacity());
53 serializeJson(json_document, output);
64 const size_t free_heap = ESP.getMaxFreeBlockSize();
65 #elif defined(USE_ESP32) 66 const size_t free_heap = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT);
69 size_t request_size = std::min(free_heap, (
size_t)(data.size() * 1.5));
71 DynamicJsonDocument json_document(request_size);
72 if (json_document.capacity() == 0) {
73 ESP_LOGE(TAG,
"Could not allocate memory for JSON document! Requested %u bytes, free heap: %u", request_size,
77 DeserializationError err = deserializeJson(json_document, data);
78 json_document.shrinkToFit();
80 JsonObject root = json_document.as<JsonObject>();
82 if (err == DeserializationError::Ok) {
85 }
else if (err == DeserializationError::NoMemory) {
86 if (request_size * 2 >= free_heap) {
87 ESP_LOGE(TAG,
"Can not allocate more memory for deserialization. Consider making source string smaller");
90 ESP_LOGV(TAG,
"Increasing memory allocation.");
94 ESP_LOGE(TAG,
"JSON parse error: %s", err.c_str());
void parse_json(const std::string &data, const json_parse_t &f)
Parse a JSON string and run the provided json parse function if it's valid.
std::function< void(JsonObject)> json_build_t
Callback function typedef for building JsonObjects.
std::string build_json(const json_build_t &f)
Build a JSON string with the provided json build function.
std::function< void(JsonObject)> json_parse_t
Callback function typedef for parsing JsonObjects.