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

相关推荐
千寻技术帮3 天前
10392_基于SpringBoot的大学迎新系统
mysql·vue·源码·springboot·代码·新生报到
DreamNotOver4 天前
Django 模板 {% if %} 标签空格被自动删除?VS Code 环境解决方案
django·html·格式化·空格
千寻技术帮6 天前
10399_基于SpringBoot的智慧养老院管理系统
java·spring boot·后端·源码·安装·代码
biyezuopinvip9 天前
基于深度学习的新闻文本分类系统的研究与设计(源码)
人工智能·深度学习·分类·源码·代码·基于深度学习的·新闻文本分类系统的研究与设计
爱笑的源码基地20 天前
云HIS系统源码,通过云原生部署和标准化接口,支持医保政策云同步及医共体建设
源码·云his·程序·代码·智慧医疗·医院管理信息系统·中小医院
千寻技术帮25 天前
10351_基于Springboot的二手交易平台
java·spring boot·mysql·毕业设计·源码·代码·二手交易
程序员鱼皮1 个月前
让 AI 分析我 3 年前写的代码,全是漏洞!
ai·程序员·互联网·软件开发·代码·编程经验
鼓掌MVP1 个月前
使用 Tbox 打造生活小妙招智能应用:一次完整的产品开发之旅
人工智能·ai·html5·mvp·demo·轻应用·tbox
牛魔王_11 个月前
ASP.NET 超时机制分析
后端·http·asp.net·超时·代码