将string转换为json对象
时间: 2023-08-31 14:06:00 浏览: 102
String转化为JSON对象
您可以使用JSON库将string转换为json对象。在C++中,可以使用RapidJSON库来实现。以下是示例代码:
```c++
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include <iostream>
#include <string>
using namespace rapidjson;
int main() {
// 将string转换为json对象
std::string jsonStr = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
Document document;
document.Parse(jsonStr.c_str());
// 从json对象中获取值
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;
}
```
输出结果:
```
Name: John
Age: 30
City: New York
```
阅读全文