Closed AcuarioCat closed 5 months ago
Hi @AcuarioCat,
file.path()
returns a const char*
, and JsonDocument
stores const char*
as a pointer and not as a copy like other string types.
The rationale behind this design is that const char*
is often used to point to a string literal, which is a read-only memory block. In this case, it's safe to store the pointer directly in the JsonDocument
.
Unfortunately, in your case, the const char*
points to a temporary string, so it's not safe to store by pointer.
The solution to your problem is to pass any other type of string.
For example, you could cast the const char*
to a char*
like so:
- jdata["t"] = file.path();
+ jdata["t"] = const_cast<char*>(file.path());
I know it's very unpleasant to use const_cast
, but fortunately, it's safe in this case because JsonDocument
will not modify the data pointed by the pointer.
If you prefer avoiding the const_cast
, you can use a String
instead, like so:
- jdata["t"] = file.path();
+ jdata["t"] = String(file.path());
This is clearly a design flaw in the library, and I hope to eliminate it someday.
Best regards, Benoit
I need to create a json array using the file directory listing from an SD card. When adding the file path to the JsonObject I end up with a corrupted json.
Strangely serializing the object that is being added shows the correct JsonObject but when added in the array it is corrupt.
If I print the file name to a char then add it the resulting json is fine. Following is my code that shows the problem and temporary solution.
The corrupted output shows the following:
Changing to the working code gives the following correct JSON