RepidJson将内容格式化后写入文件

以下是使用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文档中添加、删除或修改键值对。

相关推荐
q_q王5 天前
linux安装gitlab详细教程,本地管理源代码
git·python·gitlab·代码
xzkyd outpaper1 个月前
Android中ViewStub和View有什么区别?
android·开发语言·面试·代码
ergevv2 个月前
不同场景下git指令的搭配
git·源代码管理·代码
程序员鱼皮2 个月前
会Vibe Coding的同事:我一个人干掉整个技术部!
ai·程序员·互联网·编程·开发·代码
胖墩会武术3 个月前
Black自动格式化工具
python·格式化·black
名曰大神3 个月前
AEM6.5集成Redis详细步骤(附代码)
java·redis·demo·aem
百锦再3 个月前
Git 使用大全:从入门到精通
git·version·版本·代码·分支·code·clone
程序员鱼皮3 个月前
全球首个无限执行的 AI 出现!给我玩爽了
计算机·ai·互联网·agent·代码
程序员鱼皮3 个月前
Claude 4炸裂发布!凭什么敢称宇宙最强编程 AI?
计算机·ai·编程·开发·代码
涤生大数据4 个月前
带你玩转 Flink TumblingWindow:从理论到代码的深度探索
flink·理论·代码·tumblingwindow