cpp struct json相互转换

使用nlohmann的库

"安装"

include下载到本地可以include的位置

demo

需要再struct和class中实现to_json()和from_json()函数。

貌似cpp20可以通过反射无需手动编写to_json()和from_json(),这里不做展开

cpp 复制代码
#include <iostream>
#include "nlohmann/json.hpp"



using nlohmann::json;

struct Dog {
    std::string Name;

	// to_json 和 from_json 需要在同一命名空间下
	void to_json(json& j)
	{
		j["Name"] = Name;
	}

	void from_json(const json& j)
	{
		j.at("Name").get_to(Name);
	}
};

struct Phone {
    std::string Ptype;
    int Pnum;

	// to_json 和 from_json 需要在同一命名空间下
	void to_json(json& j)
	{
        j = {{"Ptype", Ptype},{"Pnum",Pnum}};
	}

	void from_json(const json& j)
	{
		j.at("Ptype").get_to(Ptype);
		j.at("Pnum").get_to(Pnum);
	}
};

struct User {
	std::string Name;
    int Age;
	std::map<std::string, int> Score;
    std::map<std::string, Dog> Pets;
    Phone MPhone;

    // to_json 和 from_json 需要在同一命名空间下
	void to_json(json& j)
	{
		j = json{{"Name", Name}, {"Age", Age}};
        MPhone.to_json(j["MPhone"]);    // 对象属性to_json
        for (auto& pair : Pets) {
            pair.second.to_json(j["Pets"][pair.first]); // map+对象
        }
		for (const auto& pair : Score) {    // map+int
            j["Score"][pair.first] = pair.second;
        }
	}

	void from_json(const json& j)
	{
		j.at("Name").get_to(Name);
		j.at("Age").get_to(Age);
		if(j.contains("Pets")){
            for (const auto& pair : j.at("Pets").items()) {
                Pets[pair.key()] = Dog();
                Pets[pair.key()].from_json(pair.value());
            }
        }
		for (const auto& pair : j.at("Score").items()) {  
            Score[pair.key()] = pair.value();  
        }
	}

	void from_json(std::string json_str)
	{
		json j = json::parse(json_str);
		from_json(j);
	}
};

int main(){
    User user;
    user.Name = "zhangsi";
    user.Age = 25;
    Phone p{"Mi", 1234};
    user.MPhone = p;
    user.Score["math"] = 88;
    user.Score["art"] = 89;
    user.Pets["大黄"] = Dog{"大黄"};
    user.Pets["小黑"] = Dog{"小黑"};

    json j;
    user.to_json(j);
    std::cout << "to_json: " << j.dump() << std::endl;
    std::cout << "to_json with indent:\n" << j.dump(4) << std::endl;

    User new_user;
    new_user.from_json(j);
    std::cout << "\n\nuser from json: User\nName: " << new_user.Name 
        << "\nAge: " << new_user.Age << std::endl;

}
相关推荐
_r0bin_2 小时前
前端面试准备-7
开发语言·前端·javascript·fetch·跨域·class
snow@li3 小时前
vue3+ts+vite:详细、完整的 tsconfig.json 示例 / 常见配置项及其用途
json·tsconfig.json
南郁4 小时前
007-nlohmann/json 项目应用-C++开源库108杰
c++·开源·json·nlohmann·现代c++·d2school·108杰
菠萝016 小时前
共识算法Raft系列(1)——什么是Raft?
c++·后端·算法·区块链·共识算法
海棠蚀omo6 小时前
C++笔记-C++11(一)
开发语言·c++·笔记
紫乾20146 小时前
idea json生成实体类
java·json·intellij-idea
凌佚7 小时前
rknn优化教程(一)
c++·目标检测·性能优化
Lenyiin9 小时前
《 C++ 点滴漫谈: 四十 》文本的艺术:C++ 正则表达式的高效应用之道
c++·正则表达式·lenyiin
yxc_inspire11 小时前
基于Qt的app开发第十三天
c++·qt·app·tcp·面向对象
虾球xz11 小时前
CppCon 2015 学习:Concurrency TS Editor’s Report
开发语言·c++·学习