rapidjson 获取子节点
时间: 2023-08-05 11:07:26 浏览: 43
使用 RapidJSON 获取子节点可以使用以下方法:
```c++
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
int main() {
// 假设我们有以下 JSON 字符串
const char* json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
// 解析 JSON
Document document;
document.Parse(json);
// 获取子节点
const Value& name = document["name"];
const Value& age = document["age"];
const Value& city = document["city"];
// 打印子节点的值
printf("Name: %s\n", name.GetString());
printf("Age: %d\n", age.GetInt());
printf("City: %s\n", city.GetString());
return 0;
}
```
在以上示例中,我们使用 `document["key"]` 的语法获取 JSON 中的子节点。这里的 `key` 是 JSON 中的键名。如果 JSON 中不存在该键,则会返回空节点。我们还可以使用 `GetValue()` 方法来获取节点的值,例如 `name.GetString()` 就可以获取 `"John"`。
注意,如果你使用的是 C++17 或以上的版本,可以使用结构化绑定来更方便地获取子节点:
```c++
auto [name, age, city] = document.GetObject();
```
这样就可以一次性获取所有子节点了。