jsoncpp 解析复杂json的示例
时间: 2023-10-11 08:06:00 浏览: 45
下面是使用jsoncpp解析复杂json的示例代码:
```c++
#include <iostream>
#include <fstream>
#include "json/json.h"
using namespace std;
int main()
{
// 读取json文件
ifstream ifs("data.json");
if (!ifs.is_open()) {
cout << "Failed to open file data.json" << endl;
return -1;
}
// 解析json
Json::Value root;
Json::Reader reader;
if (!reader.parse(ifs, root)) {
cout << "Failed to parse json" << endl;
ifs.close();
return -1;
}
// 获取json中的值
string name = root["name"].asString();
int age = root["age"].asInt();
// 获取json数组
Json::Value hobbies = root["hobbies"];
for (int i = 0; i < hobbies.size(); i++) {
string hobby = hobbies[i].asString();
cout << "Hobby " << i + 1 << ": " << hobby << endl;
}
// 获取json对象数组
Json::Value friends = root["friends"];
for (int i = 0; i < friends.size(); i++) {
string friend_name = friends[i]["name"].asString();
int friend_age = friends[i]["age"].asInt();
cout << "Friend " << i + 1 << ": " << friend_name << " (" << friend_age << ")" << endl;
}
ifs.close();
return 0;
}
```
假设data.json的内容如下:
```json
{
"name": "Tom",
"age": 25,
"hobbies": ["reading", "swimming", "traveling"],
"friends": [
{
"name": "John",
"age": 28
},
{
"name": "Mary",
"age": 23
},
{
"name": "David",
"age": 26
}
]
}
```
运行上面的代码,输出结果如下:
```
Hobby 1: reading
Hobby 2: swimming
Hobby 3: traveling
Friend 1: John (28)
Friend 2: Mary (23)
Friend 3: David (26)
```