{
"name" : "雄霸天下",
"no_camp" : 0,
"save_state" : 1,
"state_locked" : 1,
"default_state" : 3,
"recover_state" : 1,
"relive" :
{
"type" : "11",
"relive_item" : 200000016,
"state": [100],
"camp_relive":
[
{
"posX": 4615,
"posY": 2245
},
{
"posX": 2910,
"posY": 6378
},
{
"posX": 813,
"posY": 3589
}
]
}
}
json文件如上,如何配置jsoncpp可以查看配置jsoncpp.
其中一般键名可以直接解析,如no_camp键名对应键值为0;
可以用int no_camp = root["no_camp"].asInt();来解析。
复杂数组可以参考如下代码:
#include<string.h>
#include<json/json.h>
#include<iostream>
#include<fstream>
using namespace std;
void ReadFileJson();
int main()
{
ReadFileJson();
return 0;
}
void ReadFileJson()
{
Json::Value root;//定义根节点
Json::Reader reader;
ifstream in("C:\\Users\\57273\\Desktop\\s70301.json", ios::binary);//输入json文件的绝对路径
if (!in.is_open())
{
cout << "文件打开错误"<<endl;
return;
}
/*
//s70301.json内容如下
{
"name" : "雄霸天下",
"no_camp" : 0,
"save_state" : 1,
"state_locked" : 1,
"default_state" : 3,
"recover_state" : 1,
"relive" :
{
"type" : "11",
"relive_item" : 200000016,
"state": [100],
"camp_relive":
[
{
"posX": 4615,
"posY": 2245
},
{
"posX": 2910,
"posY": 6378
},
{
"posX": 813,
"posY": 3589
}
]
}
}
*/
if (reader.parse(in, root))
{
string name = root["name"].asString();//普通键值解析
int no_camp = root["no_camp"].asInt();
int save_state = root["save_state"].asInt();
int state_locked = root["state_locked"].asInt();
int default_state = root["default_state"].asInt();
int recover_state = root["recover_state"].asInt();
cout << "name 是 " << name << endl;
cout << "no_camp is " << no_camp << endl;
cout << "save_state is " << save_state << endl;
cout << "state_locked is " << state_locked << endl;
cout << "default_state is " << default_state << endl;
cout << "recover_state is " << recover_state << endl;
//string str ="雄霸天下";
//cout << str << endl;
string relive_type = root["relive"]["type"].asString();
int relive_relive_item = root["relive"]["relive_item"].asInt();
cout << "relive_type is " << relive_type << endl;
cout << "relive_camp_item is " << relive_relive_item << endl;
int sz = root["relive"]["state"].size();
for (int i = 0; i < sz; i++)//简单数组解析
{
int state = root["relive"]["state"][i].asInt();
cout<<"state is" << state;
}
cout << endl;
int size = root["relive"]["camp_relive"].size();
for (int i = 0; i < size; i++)//复杂数组解析
{
int posx = root["relive"]["camp_relive"][i]["posX"].asInt();
int posy = root["relive"]["camp_relive"][i]["posY"].asInt();
//cout << posx << endl;
cout << "posx is " << posx << " posy is " << posy << endl;
}
}
}
输出结果为:
其中,name键对应 的中文键值“雄霸天下”出现乱码,原因是json的编码方式和vs的编码方式不同,暂未有详细解决方案,后续解决后会写出来。