C++ 对json文件进行操作

实验所需要的库

C++标准库是不支持对json文件的操作,所以需要下载第三方库,本次实验使用的是一个比较轻量级的json库CJsonObject,地址:GitHub - Bwar/CJsonObject: Ultralightweight JSON parser in C++ based on cJSON

CJsonObject使用

简单到只需王项目添加四个文件:cJson.h cJson.c CJsonObject.hpp CJsonObject.cpp,相关文件可以到上述GitHub地址下载最新版本。在项目中添加头文件 #include "CJsonObject.h"

使用方法

官方使用方法推荐看这篇博客:推荐下cJSON的高级封装版本CJsonObject,真的很好用_cjsonobject 性能-CSDN博客

本次实验补充其他json文件的序列化和反序列化。以下面的json文件为例:

{
  "Parameters": {
     "Command": "qwer1234",
     "TaskID": 0,
     "Target": "zxc"
  },
  "Function":"asd",
  "EquipID": "poi",
  "EquipModel": "lk",
  "AppID":"xxxx-xxx-xxx-xxx",
  "TimeStamp": "2018-09-07 18:33:33"
}

CJson转换成string的方法:

std::string c = oJson.ToString();

我想读取Parameters下的Command文件,Target为string,下面的函数为转换成CJson的方式。

neb::CJsonObject oJson(Target);

打印文件

std::cout << oJson["Parameters"]("Command") << std::endl;

这样就可以了。

遍历header的值

在json中添加空的数组

例如添加r的数组这样子的:

{
	"q": "1",
	"w": 0,
	"e": "a",
	"r": [ ]
}

 这样写就可以了;

neb::CJsonObject Cjson;
Cjson.Add("q","1");
Cjson.Add("w",1);
Cjson.Add("e","a");
Cjson.AddEmptySubArray("r");	

 库里面的AddEmptySubArray这个函数就是添加空的数组的。

拼凑示例json

要拼凑的json例子:

{
    "msgName": "123", 
    "function": "qwe", 
    "tranID": 1, 
    "content": {
        "generalData": {
            "eqpID": "asd", 
            "eqpModel": "zxc"
        }, 
        "customData": {
            "header": [
                "poi"
            ], 
            "value": [
                [
                    "lkj"
                ]
            ]
        }, 
        "timestamp": "2019-11-01 15:00:01.111"
    }
}

代码:

neb::CJsonObject outputJson;
outputJson.Add("msgName","123");
outputJson.Add("function","qwe");
outputJson.Add("tranID",1);
neb::CJsonObject content;
neb::CJsonObject generalData;
generalData.Add("eqpID","asd");
generalData.Add("eqpModel","zxc");		
neb::CJsonObject customData;
neb::CJsonObject ArrayHeader;
ArrayHeader.Add("poi");
neb::CJsonObject Arrayvalue;
neb::CJsonObject Arrayvalueo;
Arrayvalueo.Add("lkj");
Arrayvalue.Add(Arrayvalueo);
customData.Add("header", ArrayHeader);
customData.Add("value", Arrayvalue);
content.Add("generalData",generalData);
content.Add("customData",customData);
content.Add("TimeStamp", GetTimeStamp());
outputJson.Add("content",content);
ConvertInformation.push_back(outputJson.ToString());

其中这一段组合不好搞。

代码对应:

neb::CJsonObject ArrayHeader;
ArrayHeader.Add("poi");
neb::CJsonObject Arrayvalue;
neb::CJsonObject Arrayvalueo;
Arrayvalueo.Add("lkj");
Arrayvalue.Add(Arrayvalueo);
customData.Add("header", ArrayHeader);
customData.Add("value", Arrayvalue);

如何遍历json的key,并取其value?

参考一篇不错的博客,说一下文中没有提及的细节,第一点,一定要使用最新版的,我之前使用老版本的是没有GetKey这个函数的。

例如:遍历D中的d1到d9所有的key,当人key读出来value也就读出来了。

{
  "A": {
      "B": "b",
      "C": 0,
       "D":[    
       { "d1": 0,
        "d2": "qwe",
        "d3": 0,
        "d4": "asd",
        "d5": 0,
        "d6": 0,
        "d7": "zxc",
        "d8": 0,
        "d9": 0
		}]  
	},
  "E": "poi",
  "F": "lkj",
  "G": "mn",
    "H":"xxxx-xxx-xxx-xxx",
  "I": "2018-09-07 18:33:33"
}

如何做:

代码:

std::vector<std::string> DName;
auto task = oJson["A"]["D"][0];
std::string strTraversingKey;
while (task.GetKey(strTraversingKey))
{
	DName.push_back(strTraversingKey);
}

运行完DName中就存储了d1到d9所有的key。

要想读取对饮的value。

auto AS = oJson["A"]["D"][0](DNames[j]);

这样AS就是对应的value的值。

---------------2023.12.15----------------------

一个简单的读写配置文件

void RWConfig(bool value)
{
	std::string filename = Utility::Instance()->GetWorkDir() + "\\config\\";
	if (value)	// 读配置文件
	{
		std::string strJson;
		
		std::ifstream file(filename + "config.json");
		if (file)
		{
			std::string line;
			while (getline(file, line))
			{
				strJson += line;
			}
			file.close(); // 关闭文件流
		}
		else
		{
			AfxMessageBox("无法打开配置文件");
		}
		std::string strIP, strFilePath, strLabName, strLogPath;
		neb::CJsonObject oJson(strJson);
		oJson.Get("bLoopTest", m_bLoopTest);
		oJson.Get("IP", strIP);
		oJson.Get("Port", m_iPort);
		oJson.Get("bOpenLog", m_bOpenLog);
		oJson.Get("CurrentFilePath", strFilePath);
		for (int i = 0; i < oJson["FilePath"].GetArraySize(); ++i)
		{
			std::string strTempFilePath = oJson["FilePath"](i);
			m_vPath.push_back(strTempFilePath);
		}
		oJson.Get("iThreadNum", m_iThreadNum);
		oJson.Get("bRightNum", m_bRightNum);
		oJson.Get("bMThread", m_bMThread);
		oJson.Get("bOneFile", m_bOneFile);
		oJson.Get("bBuildLab", m_bBuildLab);
		oJson.Get("LabName", strLabName);
		for (int i = 0; i < oJson["LabNameList"].GetArraySize(); ++i)
		{
			std::string strTempFilePath = oJson["LabNameList"](i);
			m_vLabList.push_back(strTempFilePath);
		}
		oJson.Get("LogPath", strLogPath);
		m_strIP = strIP.c_str();
		m_strFilePath = strFilePath.c_str();
		m_strLabName = strLabName.c_str();
		m_strLogPath = strLogPath.c_str();
		UpdateData(FALSE);
	}
	else  // 写配置文件
	{
		UpdateData(TRUE);
		neb::CJsonObject oJson;
		std::string strIP, strFilePath, strLabName, strLogPath;
		strIP = m_strIP.GetBuffer();
		strFilePath = m_strFilePath.GetBuffer();
		strLabName = m_strLabName.GetBuffer();
		strLogPath = m_strLogPath.GetBuffer();
		neb::CJsonObject OFilePath, OLabList;
		for (auto& value : m_vPath)
		{
			OFilePath.Add(value);
		}
		for (auto& value : m_vLabList)
		{
			OLabList.Add(value);
		}
		oJson.Add("bLoopTest", m_bLoopTest);
		oJson.Add("IP", strIP);
		oJson.Add("Port", m_iPort);
		oJson.Add("bOpenLog", m_bOpenLog);
		oJson.Add("bOneFile", m_bOneFile);
		oJson.Add("CurrentFilePath", strFilePath);
		oJson.Add("FilePath", OFilePath);
		oJson.Add("iThreadNum", m_iThreadNum);
		oJson.Add("bRightNum", m_bRightNum);
		oJson.Add("bBuildLab", m_bBuildLab);
		oJson.Add("BMThread", m_bMThread);
		oJson.Add("LabName", strLabName);
		oJson.Add("LabNameList", OLabList);
		oJson.Add("LogPath", strLogPath);	

		Utility::Instance()->m_bIsAdd = false;
		if (!std::tr2::sys::exists(std::tr2::sys::path(filename)))
		{
			create_directories(std::tr2::sys::path(filename));
		}
		Utility::Instance()->WriteInfo(filename + "config.json", oJson.ToFormattedString());
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

波雅_汉库克

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值