nlohmann/json 转 C++ 结构体
·
#include "head.h"
#include "nlohmann/json.hpp"
using nlohmann::json;
namespace ns
{
struct Person
{
std::string name = "";
int age = 0;
HTuple score;
};
// to_json 和 from_json 需要在同一命名空间下
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 以及要进行转换的结构体,写到同一命名空间下;
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)