jsoncpp数组中多个json嵌套
时间: 2023-10-11 22:08:48 浏览: 368
可以使用JsonCpp库中的Json::Value来处理多个嵌套的JSON对象。
假设我们有一个JSON数组,其中包含多个嵌套的JSON对象:
```json
[
{
"name": "John",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA"
}
},
{
"name": "Jane",
"age": 25,
"address": {
"street": "456 Oak St",
"city": "Anycity",
"state": "NY"
}
}
]
```
我们可以使用JsonCpp库将其解析为一个Json::Value对象,然后使用数组下标和键值对来访问其中的数据:
```cpp
#include <iostream>
#include <json/json.h>
int main() {
std::string json_str = R"(
[
{
"name": "John",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA"
}
},
{
"name": "Jane",
"age": 25,
"address": {
"street": "456 Oak St",
"city": "Anycity",
"state": "NY"
}
}
]
)";
Json::Value root;
Json::Reader reader;
bool success = reader.parse(json_str, root);
if (!success) {
std::cout << "Failed to parse JSON" << std::endl;
return 1;
}
for (int i = 0; i < root.size(); i++) {
std::cout << "Person " << i << ":\n";
std::cout << " Name: " << root[i]["name"].asString() << std::endl;
std::cout << " Age: " << root[i]["age"].asInt() << std::endl;
std::cout << " Address:\n";
std::cout << " Street: " << root[i]["address"]["street"].asString() << std::endl;
std::cout << " City: " << root[i]["address"]["city"].asString() << std::endl;
std::cout << " State: " << root[i]["address"]["state"].asString() << std::endl;
}
return 0;
}
```
输出结果为:
```
Person 0:
Name: John
Age: 30
Address:
Street: 123 Main St
City: Anytown
State: CA
Person 1:
Name: Jane
Age: 25
Address:
Street: 456 Oak St
City: Anycity
State: NY
```
在上面的代码中,我们首先将JSON字符串解析为Json::Value对象。然后,我们使用Json::Value的size()方法获取数组元素的数量,并使用数组下标访问每个JSON对象。最后,我们使用键值对访问每个JSON对象中的数据。
阅读全文