C++ 解析json串

时间:2023-03-10 03:31:03
C++ 解析json串

首先, C++ 解析json串,需要用到第三方库(json_vc71_libmtd.lib)。然后,VS2010,创建项目json_read,配置项目属性。最后,拷贝下面的代码就可以看到效果了。

#include "stdafx.h"
#include "../json/include/json.h" int _tmain(int argc, _TCHAR* argv[])
{
const char * str = "{\"machineCode\":\"20:20:20:20:20:20:57:4c:31:30:59:31:4d:56\",\"makeTime\":1534485879,\"sysCapacity\":{\"rptMaxNum\":2},\"trialTime\":30}";
printf("json 串:%s\n", str); Json::Reader reader;
Json::Value root;
if(reader.parse(str,root))
{
std::string machineCode = root["machineCode"].asString();
long long makeTime = root["makeTime"].asUInt();
int rptMaxNum = root["rptMaxNum"].asInt();
int trialTime = root["trialTime"].asInt(); printf("解析json串之后的值:\n");
printf("machineCode = %s\n",machineCode.c_str());
printf("makeTime = %ld\n",makeTime);
printf("rptMaxNum = %d\n",rptMaxNum);
printf("trialTIme = %d\n",trialTime); Json::Value & sysCapacity = root["sysCapacity"];
int rpt = sysCapacity["rptMaxNum"].asInt();
printf("rptMaxNum = %d\n",rpt);
}
system("pause");
return ;
}

附I:json在线格式化工具

附II:项目用到第三方库资源,有库,有头文件的时候,建议分类创建一个文件夹,便于阅读和重用。

C++ 解析json串

附录III:运行结果

C++ 解析json串