以下是使用RapidJson将JSON内容格式化后写入文件的示例代码:
cpp
#include <iostream>
#include <fstream>
#include <string>
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/writer.h"
using namespace rapidjson;
int main() {
// 创建JSON文档
Document doc;
doc.SetObject();
// 添加一些键值对
Value name("John Doe");
Value age(30);
Value hobbies(kArrayType);
hobbies.PushBack("Programming", doc.GetAllocator());
hobbies.PushBack("Reading", doc.GetAllocator());
hobbies.PushBack("Playing guitar", doc.GetAllocator());
doc.AddMember("name", name, doc.GetAllocator());
doc.AddMember("age", age, doc.GetAllocator());
doc.AddMember("hobbies", hobbies, doc.GetAllocator());
// 格式化JSON内容
StringBuffer buffer;
PrettyWriter<StringBuffer> writer(buffer);
doc.Accept(writer);
// 将JSON内容写入文件
std::string filename = "example.json";
std::ofstream ofs(filename);
if (ofs.is_open()) {
ofs << buffer.GetString();
ofs.close();
std::cout << "JSON content has been written to " << filename << std::endl;
} else {
std::cerr << "Failed to open file " << filename << std::endl;
}
return 0;
}
在上面的示例代码中,我们使用Document类创建了一个JSON文档,并使用AddMember()方法添加了几个键值对。然后,我们使用PrettyWriter类将JSON内容格式化为漂亮的字符串,并将其写入example.json文件中。你可以根据你的需要修改键值对的值,或者在JSON文档中添加、删除或修改键值对。