#include "head.h"
#include "nlohmann/json.hpp"
using nlohmann::json;
namespace ns
{
struct Person
{
std::string name = "";
int age = 0;
HTuple score;
};
void to_json(json& j, const Person& p)
{
j["name"] = p.name;
j["age"] = p.age;
j["score"] = p.score.D();
}
void from_json(const json& j, Person& p)
{
j.at("name").get_to(p.name);
j.at("age").get_to(p.age);
double d = 0.0;
j.at("score").get_to(d);
p.score = d;
}
}
int main()
{
ns::Person p{ "Tim", 10, 0.9};
json j = p;
std::cout << j << std::endl;
ns::Person p1;
j.get_to<ns::Person>(p1);
std::cout << "name:" << p1.name << std::endl;
std::cout << "age:" << p1.age << std::endl;
std::cout << "score:" << p1.score.D() << std::endl;
system("pause");
return 0;
}
注意:需要将 to_json 和 from_json 以及要进行转换的结构体,写到同一命名空间下;
|