How to store an ArduinoJson instance in a struct or copy a document?

I’m trying to save JSON objects in a C++ struct using ArduinoJSON and am hitting some snags.

My initial struct was the following:

struct Doc {
    ArduinoJson::DynamicJsonDocument data;
};

but this threw an error: " malloc: *** error for object 0xffffffffffff0098: pointer being freed was not allocated Make The Thing(18437,0x104da9880) malloc: *** set a breakpoint in malloc_error_break to debug"

*doc_instance->doc = ArduinoJson::DynamicJsonDocument(doc_byte_size);

So I guess it doesn’t like copying.

I tried using the set method as well, but this produces an empty document. I don’t understand what is happening here. Does ArduinoJSON simply not support persistence at all?

This is my full code:

    usize doc_byte_size = 64 * byte_length;
    if (!info->is_valid) {
        info->doc = (Data*)malloc(sizeof(Data));
    }
    do {
        auto doc = ArduinoJson::DynamicJsonDocument(doc_byte_size);
        DeserializationError deserialization_error = ArduinoJson::deserializeJson(doc, (const char* const)data);
        if (deserialization_error) {
            error("deserializeJson() failed: %sn", deserialization_error.c_str());
            if (strcmp(deserialization_error.c_str(), "NoMemory") != 0) {
                doc_byte_size *= 2;
                return false;
            }
        } else {
            info->doc->data.set(doc); // I thought this would copy the document
            print("received NLP datanBEGIN{n");
            std::cout << doc << std::endl; // Prints correct data
            std::cout << info->doc->data << std::endl; // prints an empty {}
            MTT_print("n}ENDn");
            break;
        }
    } while (true);

EDIT:

This documentation suggests that I should be able to do a copy, so something is definitely wrong here.

EDIT2: The deserialize function crashes when I pass in a string…

Source: StackOverflow C++

LEAVE A COMMENT