C++怎么往json字符串中写入内容
时间: 2024-03-20 08:43:17 浏览: 109
C++ JSON读写
要将内容写入JSON字符串,你需要使用一个 JSON 库。以下是使用 RapidJSON 库将内容写入JSON字符串的示例代码:
```cpp
#include <iostream>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
using namespace std;
int main() {
// 创建 JSON 对象
Document document;
document.SetObject();
// 往 JSON 对象中添加数据
Value name;
name.SetString("John", document.GetAllocator());
document.AddMember("name", name, document.GetAllocator());
Value age;
age.SetInt(30);
document.AddMember("age", age, document.GetAllocator());
Value address;
address.SetObject();
Value street;
street.SetString("123 Main St.", document.GetAllocator());
Value city;
city.SetString("Anytown", document.GetAllocator());
Value state;
state.SetString("CA", document.GetAllocator());
address.AddMember("street", street, document.GetAllocator());
address.AddMember("city", city, document.GetAllocator());
address.AddMember("state", state, document.GetAllocator());
document.AddMember("address", address, document.GetAllocator());
// 生成 JSON 字符串
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
document.Accept(writer);
// 输出 JSON 字符串
cout << buffer.GetString() << endl;
return 0;
}
```
输出结果如下:
```
{"name":"John","age":30,"address":{"street":"123 Main St.","city":"Anytown","state":"CA"}}
```
你可以根据你的需求修改代码中的数据,以生成符合你要求的 JSON 字符串。
阅读全文