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

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