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

相关推荐
梦幻加菲猫19 小时前
CSS在线格式化 - 加菲工具
前端·css·格式化
Mapmost3 天前
【数据可视化艺术·应用篇】三维管线分析如何重构城市“生命线“管理?
3d·信息可视化·性能优化·demo
Mapmost12 天前
【数据可视化艺术·实战篇】视频AI+人流可视化:如何让数据“动”起来?
人工智能·信息可视化·实时音视频·数字孪生·demo
佛州小李哥2 个月前
利用亚马逊AI代码助手生成、构建和编译一个游戏应用(下)
人工智能·科技·ai·开发·aws·代码·亚马逊云科技
艾策第三方软件测评2 个月前
审计费用差10倍?项目规模如何影响报价
代码·报价·审计
程序员鱼皮2 个月前
用 DeepSeek 给对象做个网站,她一定感动坏了
计算机·ai·程序员·互联网·网站·代码
WPG大大通3 个月前
教程 | i.MX RT1180 ECAT_digital_io DEMO 搭建(一)
经验分享·笔记·硬件工程·开发·代码·大大通
非凡的世界3 个月前
wordpress代码结构解析
解析·wordpress·代码
程序员鱼皮3 个月前
我干了两个月的大项目,开源了!
计算机·程序员·软件开发·代码·自学编程
智在碧得4 个月前
前端Monorepo实践分享
前端·代码仓库·monorepo·代码·业务组件