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

相关推荐
Evand J2 天前
【MATLAB例程】基于IMM-EKF与AOA/测距融合的二维移动目标跟踪定位
matlab·代码·定位·1024程序员节·toa·aoa
我才是银古5 天前
chat-demo 源码解析与 DeepSeek 全家桶 API 能力盘点
ai·demo·deepseek
专注仿真9 天前
知识问答模型用到的算法集详解及代码实例
python·算法·代码·大模型训练·控制算法
专注仿真17 天前
卷积神经网络(CNN)算法详解
人工智能·python·算法·代码·大模型训练
2601_967979121 个月前
当代码有了温度:程序员的键盘上,藏着人间烟火
程序员·生活·技术·代码·温情
Autumn_ing1 个月前
AI原型设计工具怎么选?可编辑原型与可运行前端适合什么场景
前端·小程序·产品经理·代码·codex·墨刀ai客户端·ai原型
伟大的车尔尼1 个月前
代码规范性与不同场景的要求
代码规范·代码·规范性
Evand J2 个月前
【MATLAB例程】三维RRT+APF避障路径规划与到达角(AOA)定位算法|三维路径优化与定位仿真例程
算法·matlab·路径规划·代码·定位·rrt·aoa
Evand J2 个月前
【MATLAB例程】三维快速扩展随机树(RRT)路径规划与到达角(AOA)、到达时间差(TDOA)融合定位,附下载链接
开发语言·matlab·代码·定位·例程
Evand J2 个月前
【MATLAB例程】三维RRT路径规划与TDOA定位算法。有中文注释、包运行成功,文末有完整代码的下载链接
matlab·路径规划·代码·定位