I know a global JsonObject shouldn't be used, but I have my reasons.
I have a JsonObject* functions and I want him to save the content of a file. With
functions=new JsonObject(jsonBuffer.as<JsonObject>());
I can access the JsonObject, but not when I leave the method. Can someone help me to understand why? (Don't give me a solution like: copy into a struct, I need a JsonObject ready to be read in all my code.
Full code:
JsonObject* functions;
void loadFunctions() {
File file = SPIFFS.open("/functions.json", "r");
if (!file) {
Serial.println("Failed to open the file");
}else{
size_t size = file.size();
if (size > 512) {
Serial.println("File size is too large");
}else{
std::unique_ptr<char[]> buf(new char[size]);
file.readBytes(buf.get(), size);
DynamicJsonDocument jsonBuffer(256);
DeserializationError error = deserializeJson(jsonBuffer, buf.get());
if (error) {
Serial.println("Failed to parse file ");
} else {
functions=new JsonObject(jsonBuffer.as<JsonObject>());
Serial.println((*functions)["test"].as<String>()); //this doesn't work in another method
}
}
}
}
-
did you call loadFunctions anywhere?ratchet freak– ratchet freak2019年09月04日 13:28:36 +00:00Commented Sep 4, 2019 at 13:28
-
Yes and the last Serial.println works, but not if I use it in another method (after this method)Maray97– Maray972019年09月04日 13:29:36 +00:00Commented Sep 4, 2019 at 13:29
1 Answer 1
jsonBuffer
is local to the function. When you leave the function the contents of jsonBuffer
are lost.
functions
just points to the internals of jsonBuffer
to get its data (to save memory).
You can either:
- Make the
jsonBuffer
global so it sticks around all the time, or - Have a secondary
DynamicJsonDocument
orStaticJsonDocument
that is global to which you copy your objects once read fromjsonBuffer
.
-
Thank you, solved by using the second choice.Maray97– Maray972019年09月04日 13:41:34 +00:00Commented Sep 4, 2019 at 13:41