0

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
 }
 }
 }
}
VE7JRO
2,51519 gold badges27 silver badges29 bronze badges
asked Sep 4, 2019 at 13:24
2
  • did you call loadFunctions anywhere? Commented 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) Commented Sep 4, 2019 at 13:29

1 Answer 1

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 or StaticJsonDocument that is global to which you copy your objects once read from jsonBuffer.
answered Sep 4, 2019 at 13:36
1
  • Thank you, solved by using the second choice. Commented Sep 4, 2019 at 13:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.