string 转 json
时间: 2024-05-19 09:08:24 浏览: 14
将字符串转换为JSON是一种常见的操作,可以使用不同的编程语言和库来实现。以下是使用C++和RapidJSON库将字符串转换为JSON的示例:
```cpp
#include <iostream>
#include <string>
#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
int main() {
std::string jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
rapidjson::Document document;
document.Parse(jsonString.c_str());
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
document.Accept(writer);
std::cout << buffer.GetString() << std::endl;
return 0;
}
```
上述代码使用了RapidJSON库来解析和生成JSON。首先,我们将JSON字符串传递给`Parse`函数,将其解析为一个`Document`对象。然后,我们创建一个`StringBuffer`和一个`Writer`对象,用于将`Document`对象转换为字符串。最后,我们通过调用`Accept`函数将`Document`对象写入`StringBuffer`中,并使用`GetString`函数获取最终的JSON字符串。
相关推荐
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)