-
-
Notifications
You must be signed in to change notification settings - Fork 6.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
(De-)Serialization of std::variant with namespaces #2208
Comments
I have found a solution for the problem. If the adl_serializer is specified with the variant type instead of providing from_json/to_json functions, the compiler is happy. Why the approach with from_json/to_json does not work, i cannot extract from the documentation (https://github.com/nlohmann/json#arbitrary-types-conversions) namespace nlohmann
{
template <> struct adl_serializer<FoobarVariant>
{
static void to_json(json &obj, const FoobarVariant &foo)
{
if (std::holds_alternative<foo::Foobar>(foo))
foo::to_json(obj, std::get<foo::Foobar>(foo));
else if (std::holds_alternative<bar::Foobar>(foo))
bar::to_json(obj, std::get<bar::Foobar>(foo));
else
throw std::runtime_error("non exhaustive pattern match in void "
"to_json(json &obj, const FoobarVariant &foo)");
}
static void from_json(const json &obj, FoobarVariant &foo)
{
auto t = obj["type"].get<std::string>();
if (t == "foo::Foobar")
foo::from_json(obj, std::get<foo::Foobar>(foo));
else if (t == "bar::Foobar")
bar::from_json(obj, std::get<bar::Foobar>(foo));
else
throw std::runtime_error(
"non exhaustive pattern match in void "
"from_json(const json &obj, FoobarVariant &foo)");
}
}; |
Thank you @wbitesi , it is a more concise method than my implementation. |
Another alternative: #3436 (comment) For anyone that finds this in the future, and has this same question:
the answer is here: https://github.com/nlohmann/json#how-do-i-convert-third-party-types
|
I have problems with (de-)serialization with std::variant<...> if the variant types are in different namespaces (see the minimal example below, just compile with -std=c++17 for std::variant). If i put the types in the global namespace, the variant part just works. Anyone an idea how to use namespaces in the variant with json deserialization?
The text was updated successfully, but these errors were encountered: