使用nlohmann::json库来实现Json和C++自定义结构体互相转换。
【转载】Json和C++自定义结构体互相转换1
struct MyContainer {
std::string name;
std::string address;
int age;
list<string> lst;
double score;
};
//1.重载转换函数
void to_json(nlohmann::json& j, const MyContainer& p) {
j = json{ {"name", p.name}, {"address", p.address}, {"score", p.score},{"age",p.age},{"lst",p.lst} };
}
void from_json(const nlohmann::json& j, MyContainer& p) {
j.at("name").get_to(p.name);
j.at("address").get_to(p.address);
j.at("score").get_to(p.score);
j.at("age").get_to(p.age);
j.at("lst").get_to(p.lst);
int main()
{
MyContainer c;
c.age = 3;
c.name = "jnoy";
c.score = 6;
c.lst.push_back("aa");
c.lst.push_back("cc");
json j = c;//将结构体转换成json对象
std::string str= j.dump();//转换字符串
std::cout << str << std::endl;
//必须在同名称空间,实现to_json,from_json
auto p= j.get<MyContainer>();//转换结构体
// json k = c;
return 0;
}