c++ json解析
时间: 2023-09-11 10:12:54 浏览: 45
你可以使用第三方库来解析 JSON 数据,比如 RapidJSON、nlohmann/json 等。以下是一个使用 RapidJSON 库解析 JSON 的示例代码:
```cpp
#include <iostream>
#include <string>
#include "rapidjson/document.h"
int main() {
std::string jsonStr = R"({"name": "Alice", "age": 25, "city": "New York"})";
// 解析 JSON 字符串
rapidjson::Document document;
document.Parse(jsonStr.c_str());
// 获取字段值
std::string name = document["name"].GetString();
int age = document["age"].GetInt();
std::string city = document["city"].GetString();
// 打印结果
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "City: " << city << std::endl;
return 0;
}
```
以上代码中,我们使用 RapidJSON 库解析了一个包含 name、age、city 字段的 JSON 字符串,并获取了各个字段的值。你可以根据自己的需要修改 JSON 字符串和字段名称。记得在编译时链接 RapidJSON 库,并在代码中包含相应的头文件。