Replies: 2 comments
-
You can serialize variants with this: namespace nlohmann {
template <typename ...Args>
struct adl_serializer<std::variant<Args...>> {
static void to_json(json& j, std::variant<Args...> const& v) {
std::visit([&](auto&& value) {
j = std::forward<decltype(value)>(value);
}, v);
}
};
} See #1261 for a discussion. |
Beta Was this translation helpful? Give feedback.
0 replies
-
Here's some code I use that also lets you load JSON to variants. It creates a mapping between JSON and C++ types so that you can use exactly those types in your variants (you may need to change those types according to your needs). It allows you to use variants containing any subset of those types. namespace nlohmann {
template <typename ...Args>
struct adl_serializer<std::variant<Args...>> {
template<typename T>
struct deserializer {
template<typename U>
static constexpr bool contained() {
return false;
}
template<typename U, typename V, typename... Others>
static constexpr bool contained() {
if constexpr (std::is_same_v<U, V>) return true;
else return contained<U, Others...>();
}
template<typename... U>
static inline std::enable_if_t<contained<T, U...>(), bool> load(
const json &j, std::variant<U...> &v) {
v = j.get<T>();
return true;
}
template<typename... U>
static constexpr std::enable_if_t<!contained<T, U...>(), bool> load(
const json &j, std::variant<U...> &) {
return false;
}
};
static void to_json(json& j, std::variant<Args...> const& v) {
std::visit([&](auto&& value) {
j = std::forward<decltype(value)>(value);
}, v);
}
static void from_json(json const& j, std::variant<Args...>& v) {
if (j.is_string()) {
if (deserializer<std::string>::load(j, v)) return;
} else if (j.is_number_integer()) {
if (deserializer<int64_t>::load(j, v)) return;
} else if (j.is_boolean()) {
if (deserializer<bool>::load(j, v)) return;
} else if (j.is_null()) {
if (deserializer<std::nullptr_t>::load(j, v)) return;
} else if (j.is_number_float()) {
if (deserializer<double>::load(j, v)) return;
}
throw detail::type_error::create(302, "value has unsupported type " + std::string(j.type_name()));
}
};
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
nlohmann::json obj;
std::variant<std::nullptr_t, bool, int, double, std::string> var = nullptr;
obj["var"] = var; // not support
further
std::map<std::string, std::variant<std::nullptr_t, bool, int, double, std::string>> c_map{ {"one", false}, {"two", 2}, {"three", nullptr} };
obj["obj"] = c_map;
Beta Was this translation helpful? Give feedback.
All reactions