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

相关推荐
佛州小李哥6 天前
利用亚马逊AI代码助手生成、构建和编译一个游戏应用(下)
人工智能·科技·ai·开发·aws·代码·亚马逊云科技
艾策第三方软件测评7 天前
审计费用差10倍?项目规模如何影响报价
代码·报价·审计
程序员鱼皮9 天前
用 DeepSeek 给对象做个网站,她一定感动坏了
计算机·ai·程序员·互联网·网站·代码
WPG大大通17 天前
教程 | i.MX RT1180 ECAT_digital_io DEMO 搭建(一)
经验分享·笔记·硬件工程·开发·代码·大大通
非凡的世界25 天前
wordpress代码结构解析
解析·wordpress·代码
程序员鱼皮1 个月前
我干了两个月的大项目,开源了!
计算机·程序员·软件开发·代码·自学编程
智在碧得2 个月前
前端Monorepo实践分享
前端·代码仓库·monorepo·代码·业务组件
sdaxue.com2 个月前
帝国cms电脑pc站url跳转到手机站url的方法
网站·代码·帝国cms·手机站·站长
程序员鱼皮2 个月前
第一次参加实习,我祛魅了!
后端·计算机·互联网·软件开发·求职·代码·编程经验
梦幻加菲猫2 个月前
XML 在线格式化 - 加菲工具
xml·前端·格式化