cpp17 std::optional and std::variant to/from json conversion
This pr would add std::optional and std::variant serialization/deserialization extension to the Json-cast example files for the cpp17 branch.
Hello. Thanks for the PR Can you please show some examples of usage? E.g. if I have a class with std::optional/std::variant, how does it get serialized?
And to be honest, I feel like this adds quite a lot of complexity and might be better be its own example (because JsonCast example was meant to be as simple as possible to give people ideas how to write serializers for other formats)
Hello. I totally agree, it adds a lot of complexity. Would it be ok to make a new examples folder? I have also made some GTests that I could add, that could serve as an example.
My intention was:
1.) std::optional
struct Person
{
std::string name;
int age;
std::optional<int> weight;
}
template <>
inline auto registerMembers<Person>()
{
return members(
member("name", &Person::name),
member("age", &Person::age),
member("weight", &Person::weight)
);
}
Serialization -> When the optional field is set, it serializes as it would be a normal member, when its empty, no json entry is created for it. Deserialization <- When the Json key is not found for the optional element, the optional stays unset, if there is a json entry, its value gets emplaced in the optional member. Compared to the "normal" fields, no exception get raised if the according entry for the optional member is not found in the json representation.
2.) std::variant
Serialization -> The actual emplaced Type will be serialized and an additional key-value pair is added: __type_index__: <index in variant> to avoid ambiguities
Deserialization <- The code tries to deserialize the json entry corresponding to the type indexed by the __type_index__ field
Note: I can imagine there are better(/more modern) ways to iterate over the tuple than I did, I am open for every improvement
- Please make a structure like this:
example/
dependencies/nlohmann_json/ - nlohmann's JSON lib
basic_json/ - original example with JsonCast
optional_variant_json/ - your example with std::optional and std::variant
- Your example should only work for
std::optionalandstd::variant(and possibly withstd::stringand int). It shouldn't copy all of JsonCast (e.g. functions which work withstd::unordered_mapandstd::vector), because copy-paste is bad. Also, themain.cppshould have clear examples of jsons which will be obtained when you serialize the data. I don't see__type_index__in example's main.cpp, and it should be mentioned.