json文件示例:
{“http”:[{
"1":{
"fun_id" : 1,
"run_begin_time" : "2022-07-08-15-24-01"
},
"2":{
"data" : {
"0" : 75.77000000000001,
"1" : 54.830000000000013,
"2" : 58.180000000000007,
"3" : 66.030000000000001,
"4" : 56.140000000000001,
"5" : 64.310000000000002,
"6" : 67.730000000000004,
"7" : 55.400000000000006,
"8" : 60.540000000000006,
"9" : 55.850000000000001
}
},
"3":{
"resultID" : 0,
"run_end_time" : "2022-07-08-15-24-04"
}
}]
}
c++代码:
//读取json文件
#include “stdafx.h”
#include
#include
#include <json/json.h>
#include
//#include <assert.h>
using namespace std;
void readJson();
int main1()
{
readJson();
system(“pause”);
return 0;
}
void readJson()
{
Json::Reader reader;
Json::Value root;
string jsonPath = “E:\Point_EV_Spatial\res_httpServer\json\cloud_tower_all-2022-07-08-15-24-00.json”;
ifstream is(jsonPath, ios::binary);
if (!is.is_open())
{
cout << "Error opening" << endl;
return;
}
reader.parse(is, root);
Json::StyledWriter sw;
cout << sw.write(root);
int j = root["http"].size();
cout << root["http"][j - 1]["2"]["data"]["1"].asString();
int resultID = root["resultID"].asInt();
if (root["s"].type()==Json::nullValue) //判断json中是否存在s节点
{
cout << "不存在的节点"<<endl;
}
if (resultID == 0)
{
string begintime = root["http"][j-1]["1"]["run_begin_time"].asString();
cout << "开始时间 : " << begintime << endl;
const Json::Value arrayobj = root["http"][j - 1]["2"]["data"];
cout << arrayobj<<endl; //代表data数据集
//string data = root["http"][j - 1]["2"]["data"][i].asString();
for (unsigned int i=0; i<arrayobj.size(); i++)
{
string index = to_string(i) ; //将int转字符串
cout << arrayobj[index]<<endl; //arrayobj[i]不行,毕竟将i转为字符串
}
}
else if(resultID!=0)
{
//程序还没运行
cout << "Error";
}
is.close();
}