#include <iostream>
#include <string>
#include <variant>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace std;
namespace nlohmann {
template <typename T, typename... Ts>
void variant_from_json(const nlohmann::json &j, std::variant<Ts...> &data) {
try {
data = j.get<T>();
} catch (...) {
}
}
template <typename... Ts>
struct adl_serializer<std::variant<Ts...>>
{
static void to_json(nlohmann::json &j, const std::variant<Ts...> &data) {
std::visit([&j](const auto &v) { j = v; }, data);
}
static void from_json(const nlohmann::json &j, std::variant<Ts...> &data) {
(variant_from_json<Ts>(j, data), ...);
}
};
};
int main()
{
using variantT = variant<int, string>;
variantT v1(12);
json j1 = v1;
cout<<j1<<endl;
json j2 = "hi";
variantT v2 = j2;
cout<<get<string>(v2)<<endl;
return 0;
}
运行程序输出:
12
hi