c++把json读成指针
时间: 2023-10-01 10:03:27 浏览: 41
你可以使用第三方库,比如jsoncpp来解析JSON并将其存储为指针。以下是一个示例代码:
```cpp
#include <iostream>
#include <json/json.h>
int main() {
std::string jsonStr = R"({"name": "John", "age": 30, "city": "New York"})";
Json::CharReaderBuilder reader;
Json::Value root;
std::string errors;
std::istringstream jsonStream(jsonStr);
if (!Json::parseFromStream(reader, jsonStream, &root, &errors)) {
std::cout << "Failed to parse JSON: " << errors << std::endl;
return 1;
}
// 将JSON存储为指针
Json::Value* rootPtr = &root;
// 使用指针访问JSON数据
std::string name = (*rootPtr)["name"].asString();
int age = (*rootPtr)["age"].asInt();
std::string city = (*rootPtr)["city"].asString();
// 输出结果
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "City: " << city << std::endl;
return 0;
}
```
上述代码使用了jsoncpp库来解析JSON字符串,并将其存储为指向Json::Value的指针。你可以使用指针访问JSON数据,从而读取相应的值。请确保在编译和运行代码之前,已经安装并正确配置了jsoncpp库。