ArduinoJson null after function return

Hello, I'm trying to set a config (StaticJsonDocument) from a "load" method and later get that data from a different function. It's almost like shown here

#include <ArduinoJson.h>
StaticJsonDocument<200> doc;
void load() {
    File config = LittleFS.open("/config.json", "r");
    std::unique_ptr<char[]> buf(new char[config.size()]);
    config.readBytes(buf.get(), config.size());
    deserializeJson(doc, buf.get());
    Serial.println(doc["key"].as<String>()); // -> returns the value
}
void access() {
    Serial.println(doc["key"].as<String>()); // -> returns null
}
void setup() {
    load();
    access();
}

But as soon as the "load" function is done, the doc["key"] becomes a nullptr. Within the "access" function I cannot print anything.

How would I solve this?

he function deserializeJson() parses a JSON input and puts the result in a JsonDocument.

  • For a read-only input, it duplicates the strings in the input document. This duplication consumes additional space in the JsonDocument.
  • For a writeable input, it stores pointers to the strings in the input buffer. This is the zero-copy mode.

here you have a writeable buffer, so it's copy mode but the buffer goes out of scope and is released at the end of load(). You need to trick the compiler into calling the right function, so probably if you cast to const char* then the data should be duplicated into your doc.

PS/ you did not close the file.

Thats it! I changed the line for the deserializeJson to this

    deserializeJson(doc, String(buf.get()).c_str());

it's working now!

And thanks for the PS. I really didn't have that in my code!

have you tried

    deserializeJson(doc, (const char *) buf.get());

with String() you are duplicating again the data.