I'm utilizing this json library: https://arduinojson.org/
I am attempting to write a function that creates a response object, and wraps an already built json document:
void sendResponse(
ResponseType state,
JsonDocument *response
) {
DynamicJsonDocument doc(256);
doc[F("state")] = responseTypeFromEnum(state);
doc[F("response")] = response; //breaks; how to do?
this->sendJson(&doc);
}
This fails of course, and I don't see a great solution anywhere...
I know I could use createNestedObject()
, but this seems to require re-creating the given json object by hand? This would be a sub-optimal case.
Is there a way to easily wrap an existing JsonDocument in another?
Looking to take
{
"some": "other document"
}
And wrap it like
{
"state":"OK"
"response": {
"some": "other document"
}
}
1 Answer 1
You can add a JsonDocument
inside another one, but you must pass the document by value, not by pointer.
Since you receive a pointer, you need to dereference it before trying to assign:
doc[F("response")] = *response;
Node 1: you could avoid this problem by passing response
by reference, like so:
void sendResponse(ResponseType state, const JsonDocument &response) {
DynamicJsonDocument doc(256);
doc[F("state")] = responseTypeFromEnum(state);
doc[F("response")] = response;
this->sendJson(doc);
}
Node 2: calling the assignment operator (=
) causes a deep copy of the response
document. You could avoid this copy by calling shallowCopy()
instead:
doc[F("response")].shallowCopy(response);
Node 3: unfortunately shallowCopy()
is unavailable on ArduinoJson 7.
-
1Interesting on Node 3.. Looks like
shallowCopy()
only came out in 6, so why is it gone in 7? Is there no equivalent there? Looks like I'm currently using 6 though, compiles fine for me. Thanks for the pointSnappawapa– Snappawapa2023年08月31日 14:42:01 +00:00Commented Aug 31, 2023 at 14:42 -
Sorry, "Node" was supposed to be "Note" :-) Indeed, I removed
shallowCopy()
becauseJsonDocument
doesn't store pointers to variants anymore. Instead, it stores indexes relative to the current document. It would be possible to recreateshallowCopy()
but it would require extra plumbing (so extra weight), and I don't think it's worth it.Benoit Blanchon– Benoit Blanchon2023年08月31日 15:16:15 +00:00Commented Aug 31, 2023 at 15:16 -
Thanks for the note! I might personally argue that some extra code plumbing is worth a potentially large amount of end RAM usage savings to support :) (assuming it's not astronomically hard to do so)Snappawapa– Snappawapa2023年08月31日 15:24:22 +00:00Commented Aug 31, 2023 at 15:24
-
Right, but on the other hand, it's not that difficult to avoid this situation. See the the upgrade guide for an example.Benoit Blanchon– Benoit Blanchon2023年08月31日 16:16:46 +00:00Commented Aug 31, 2023 at 16:16