Sorry if this is a naive question but I am relatively new to the platform. I am currently building an app for an ESP32.
I would like to add a json custom converter to make it easier to code serialization and deserialization to some custom classes. As I understand it you can set up custom converters so that you can then use code like:
//deserialize
myClass = doc["mydata"];
//serialize
doc["mydata"] = myclass;
There is a tutorial (https://arduinojson.org/news/2021/05/04/version-6-18-0/) which sort of explains how to add a custom converter. It talks about adding a convertToJson()
and convertFromJson()
function and says “To do so, we need to define functions with well-known signatures, and ArduinoJson will automatically call these functions. ” .
I understand the code. What I don’t understand from that tutorial is “where” such code gets added or how it is integrated so that ArduinoJson can as they say “automatically” use it.
Can anyone point me to or provide an example or tutorial that fills in the details.
3
After some more research prompted by user12002570’s cryptic comment, I have stumbled upon the correct method and also some details on how I found the answer and what the answer is, so that might help others with this and similar problems.
First, I made a simple class:
class myClass {
};
class app {
void setup() {
// pseudocode to get Json document
JsonDocument doc;
DeserializationError error = deserializeJson(doc,docName);
myClass myclass = doc["mydata"]; //this line causes compile error
}
};
As a test I just compiled this and had an error message that gave me the clue:
.pio/libdeps/esp32dev/ArduinoJson/src/ArduinoJson/Variant/ConverterImpl.hpp:40:20: error: no matching function for call to 'convertFromJson(ArduinoJson::V710PB22::JsonVariantConst&, myClass&)'
convertFromJson(src, result); // Error here? See https://arduinojson.org/v7/unsupported-as/
Following this link (https://arduinojson.org/v7/unsupported-as/) had the description of the problem and the answer and also gave clue as to the “how” and “where”. The key statement is You must declare this function in the same namespace as the type you want to convert to JSON so that the compiler can find it through ADL.
So the answer to the “how” it integrates is the compiler looks for an appropriate function in the same namespace as the myClass
type and uses compiler ADL to insert the convertFromJson()
function. (P.S. I need to learn what ADL is all about).
The answer to “where” is … I placed the functions in the cpp file containing class definitions, but these are stand alone functions (??? must find out why?), and not part of any of the classes. The code here compiles ok.
class myClass {
};
class app {
void setup() {
// pseudocode to get Json document
JsonDocument doc;
DeserializationError error = deserializeJson(doc,docName);
myClass myclass= doc["mydata"];
}
};
void convertFromJson(JsonVariantConst src, myClass& dst) {
// do some fancy conversion stuff
}