7 static const char *
const TAG =
"json";
9 static std::vector<char> global_json_build_buffer;
17 auto free_heap = ALLOCATOR.get_max_free_block_size();
18 size_t request_size = std::min(free_heap, (
size_t) 512);
20 ESP_LOGV(TAG,
"Attempting to allocate %zu bytes for JSON serialization", request_size);
21 DynamicJsonDocument json_document(request_size);
22 if (json_document.capacity() == 0) {
24 "Could not allocate memory for JSON document! Requested %zu bytes, largest free heap block: %zu bytes",
25 request_size, free_heap);
28 JsonObject root = json_document.to<JsonObject>();
30 if (json_document.overflowed()) {
31 if (request_size == free_heap) {
32 ESP_LOGE(TAG,
"Could not allocate memory for JSON document! Overflowed largest free heap block: %zu bytes",
36 request_size = std::min(request_size * 2, free_heap);
39 json_document.shrinkToFit();
40 ESP_LOGV(TAG,
"Size after shrink %zu bytes", json_document.capacity());
42 serializeJson(json_document, output);
52 auto free_heap = ALLOCATOR.get_max_free_block_size();
53 size_t request_size = std::min(free_heap, (
size_t) (data.size() * 1.5));
55 DynamicJsonDocument json_document(request_size);
56 if (json_document.capacity() == 0) {
57 ESP_LOGE(TAG,
"Could not allocate memory for JSON document! Requested %zu bytes, free heap: %zu", request_size,
61 DeserializationError err = deserializeJson(json_document, data);
62 json_document.shrinkToFit();
64 JsonObject root = json_document.as<JsonObject>();
66 if (err == DeserializationError::Ok) {
68 }
else if (err == DeserializationError::NoMemory) {
69 if (request_size * 2 >= free_heap) {
70 ESP_LOGE(TAG,
"Can not allocate more memory for deserialization. Consider making source string smaller");
73 ESP_LOGV(TAG,
"Increasing memory allocation.");
77 ESP_LOGE(TAG,
"JSON parse error: %s", err.c_str());
bool 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::function< bool(JsonObject)> json_parse_t
Callback function typedef for parsing JsonObjects.
std::string build_json(const json_build_t &f)
Build a JSON string with the provided json build function.
Implementation of SPI Controller mode.