用cplusplus从{"1":{"route_info_arr":[{"gateway":"110.110.110.254","ip":"110.110.110.101","netmask":"255.255.255.0"}]}}读出动态的key “1”
时间: 2023-09-03 16:08:21 浏览: 45
可以使用 rapidjson 库来解析 JSON 数据。代码如下:
```cpp
#include <iostream>
#include "rapidjson/document.h"
using namespace rapidjson;
int main() {
// 定义 JSON 字符串
const char* jsonStr = "{\"1\":{\"route_info_arr\":[{\"gateway\":\"110.110.110.254\",\"ip\":\"110.110.110.101\",\"netmask\":\"255.255.255.0\"}]}}";
// 解析 JSON 字符串
Document doc;
doc.Parse(jsonStr);
// 获取动态的 key
for (auto itr = doc.MemberBegin(); itr != doc.MemberEnd(); ++itr) {
std::string key = itr->name.GetString();
// 打印 key
std::cout << key << std::endl;
// 获取 route_info_arr 数组
const Value& routeArr = itr->value["route_info_arr"];
const SizeType nSize = routeArr.Size();
// 打印数组内容
for (SizeType i = 0; i < nSize; ++i) {
const Value& item = routeArr[i];
std::string gateway = item["gateway"].GetString();
std::string ip = item["ip"].GetString();
std::string netmask = item["netmask"].GetString();
std::cout << "gateway: " << gateway << std::endl;
std::cout << "ip: " << ip << std::endl;
std::cout << "netmask: " << netmask << std::endl;
}
}
return 0;
}
```
输出结果为:
```
1
gateway: 110.110.110.254
ip: 110.110.110.101
netmask: 255.255.255.0
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)