C++ 如何使用RapidJson 写入文件

 更新时间:2024年04月01日 10:38:33   作者:SUNX-T  
RapidJSON 是只有头文件的 C++ 库, 不需要编译, 可以直接在项目中使用, 只需把 include/rapidjson 目录复制至系统或项目的 include 目录即可,下面给大家分享C++ 如何使用RapidJson 写入文件,感兴趣的朋友跟随小编一起看看吧

使用RapidJson写入文件(C++)

本文部分内容由AI生成

最初,我希望能够使用RapidJson 向文件中写入一个三级json。其二级json是由for循环计算生成的。但是写来写去,发现有很多乱码,好像是字符串空间在写入流之前就销毁的原因?(不确定)于是,使用AI生成了以下例子。

基于C++ 对json文件进行写入

#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/prettywriter.h> // for prettywriter
#include <rapidjson/filereadstream.h>
#include <rapidjson/filewritestream.h>
#include <cstdio>
using namespace rapidjson;
int main() {
    // 创建一个JSON对象
    Document d;
    d.SetObject();
    Document::AllocatorType& allocator = d.GetAllocator();
    d.AddMember("name", Value().SetString("John Doe", allocator), allocator);
    d.AddMember("age", 30, allocator);
    d.AddMember("is_student", false, allocator);
    // 写入文件
    FILE* fp = fopen("example.json", "wb"); // 非Windows平台可能需要使用 "w"
    char writeBuffer[65536];
    FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
    PrettyWriter<FileWriteStream> writer(os);   // 注意,可以不使用PrettyWriter,不过,写出来的结构不好看,Pretty会将json写成树结构
    d.Accept(writer);
    fclose(fp);
    // 读取文件
    fp = fopen("example.json", "rb"); // 非Windows平台可能需要使用 "r"
    char readBuffer[65536];
    FileReadStream is(fp, readBuffer, sizeof(readBuffer));
    Document d2;
    d2.ParseStream(is);
    fclose(fp);
    // 输出读取的内容(简单示例)
    printf("Name: %s\n", d2["name"].GetString());
    printf("Age: %d\n", d2["age"].GetInt());
    printf("Is Student: %s\n", d2["is_student"].GetBool() ? "true" : "false");
    return 0;
}

使用RapidJson对文件进行写入,写入的是一个二级json(包含多个对象)

#include <cstdio>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/prettywriter.h> // for PrettyWriter
#include <rapidjson/filewritestream.h>
using namespace rapidjson;
int main() {
    // 创建一个JSON文档,这将作为我们的根对象
    Document document;
    document.SetObject();
    Document::AllocatorType& allocator = document.GetAllocator();
    // 创建一个JSON数组
    Value array(kArrayType);
    // 创建第一个对象并添加到数组
    Value object1(kObjectType);
    object1.AddMember("id", 1, allocator);
    object1.AddMember("name", "John Doe", allocator);
    array.PushBack(object1, allocator);
    // 创建第二个对象并添加到数组
    Value object2(kObjectType);
    object2.AddMember("id", 2, allocator);
    object2.AddMember("name", "Jane Smith", allocator);
    array.PushBack(object2, allocator);
    // 创建第三个对象并添加到数组
    Value object3(kObjectType);
    object3.AddMember("id", 3, allocator);
    object3.AddMember("name", "Alice Johnson", allocator);
    array.PushBack(object3, allocator);
    // 将数组添加到根对象
    document.AddMember("users", array, allocator);
    // 将JSON写入文件
    FILE* fp = fopen("output.json", "wb"); // 非Windows平台可能需要使用 "w"
    char writeBuffer[65536];
    FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
    PrettyWriter<FileWriteStream> writer(os);
    document.Accept(writer);
    fclose(fp);
    return 0;
}

使用RapidJson写一个包含多个对象的二级json文件,使用for循环

#include <cstdio>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/prettywriter.h> // for PrettyWriter
#include <rapidjson/filewritestream.h>
using namespace rapidjson;
int main() {
    // 创建一个JSON文档,作为根对象
    Document document;
    document.SetObject();
    Document::AllocatorType& allocator = document.GetAllocator();
    // 创建一个JSON数组
    Value usersArray(kArrayType);
    // 使用for循环生成多个用户对象
    for (int i = 1; i <= 5; ++i) {
        Value userObject(kObjectType);
        // 为了示例简单,这里使用i作为id和name的一部分
        userObject.AddMember("id", i, allocator);
        // 创建一个具有动态字符串的Value
        std::string name = "User " + std::to_string(i);
        Value nameValue;
        nameValue.SetString(name.c_str(), static_cast<SizeType>(name.length()), allocator);
        userObject.AddMember("name", nameValue, allocator);
        // 将用户对象添加到数组中
        usersArray.PushBack(userObject, allocator);
    }
    // 将数组添加到根对象中
    document.AddMember("users", usersArray, allocator);
    // 写入文件
    FILE* fp = fopen("users_output.json", "wb"); // 非Windows平台可能需要使用 "w"
    char writeBuffer[65536];
    FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
    PrettyWriter<FileWriteStream> writer(os);
    document.Accept(writer);
    fclose(fp);
    return 0;
}

这段代码首先创建了一个根JSON文档document和一个数组usersArray。通过for循环,我们创建了五个用户对象,每个对象包含idname字段,其中name是通过将循环的索引i转换为字符串并与"User "连接得到的。这些用户对象被添加到usersArray中,最后这个数组被添加到根文档中,并通过PrettyWriter写入到名为users_output.json的文件中。

结果:

{
    "users": [
        {
            "id": 1,
            "name": "User 1"
        },
        {
            "id": 2,
            "name": "User 2"
        },
        {
            "id": 3,
            "name": "User 3"
        },
        {
            "id": 4,
            "name": "User 4"
        },
        {
            "id": 5,
            "name": "User 5"
        }
    ]
}

使用RapidJson向文件中写入一个三级json

#include <cstdio>
#include <string>
#include <rapidjson/document.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/filewritestream.h>
using namespace rapidjson;
int main() {
    // 创建根文档
    Document document;
    document.SetObject();
    Document::AllocatorType& allocator = document.GetAllocator();
    // 创建一个JSON数组用于存放部门信息
    Value departmentsArray(kArrayType);
    // 使用for循环添加部门和员工
    for (int depId = 1; depId <= 3; ++depId) {
        Value departmentObject(kObjectType);
        // 部门ID和名称
        departmentObject.AddMember("departmentId", depId, allocator);
        std::string depName = "Department " + std::to_string(depId);
        Value depNameValue;
        depNameValue.SetString(depName.c_str(), allocator);
        departmentObject.AddMember("name", depNameValue, allocator);
        // 为每个部门创建员工数组
        Value employeesArray(kArrayType);
        for (int empId = 1; empId <= 4; ++empId) {
            Value employeeObject(kObjectType);
            employeeObject.AddMember("employeeId", empId, allocator);
            std::string empName = "Employee " + std::to_string(empId) + " of Dep " + std::to_string(depId);
            Value empNameValue;
            empNameValue.SetString(empName.c_str(), allocator);
            employeeObject.AddMember("name", empNameValue, allocator);
            // 将员工对象添加到员工数组
            employeesArray.PushBack(employeeObject, allocator);
        }
        // 将员工数组添加到部门对象
        departmentObject.AddMember("employees", employeesArray, allocator);
        // 将部门对象添加到部门数组
        departmentsArray.PushBack(departmentObject, allocator);
    }
    // 将部门数组添加到根文档
    document.AddMember("departments", departmentsArray, allocator);
    // 写入文件
    FILE* fp = fopen("departments_output.json", "wb"); // 非Windows平台可能需要使用 "w"
    char writeBuffer[65536];
    FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
    PrettyWriter<FileWriteStream> writer(os);
    document.Accept(writer);
    fclose(fp);
    return 0;
}
  • 我们创建了一个根文档document,它包含了一个名为departments的数组。
  • 通过外层for循环,我们为每个部门创建了一个包含基本信息(ID和名称)的对象,并为每个部门创建了一个名为employees的数组。
  • 内层for循环为每个部门创建了几个员工对象,每个员工对象包含员工的ID和名称。
  • 最后,每个部门对象(包括其员工数组)被添加到部门数组中,整个部门数组最终被添加到根文档中,并通过PrettyWriter写入到一个名为departments_output.json的文件中。

结果

{
    "departments": [
        {
            "departmentId": 1,
            "name": "Department 1",
            "employees": [
                {
                    "employeeId": 1,
                    "name": "Employee 1 of Dep 1"
                },
                {
                    "employeeId": 2,
                    "name": "Employee 2 of Dep 1"
                },
                {
                    "employeeId": 3,
                    "name": "Employee 3 of Dep 1"
                },
                {
                    "employeeId": 4,
                    "name": "Employee 4 of Dep 1"
                }
            ]
        },
        {
            "departmentId": 2,
            "name": "Department 2",
            "employees": [
                {
                    "employeeId": 1,
                    "name": "Employee 1 of Dep 2"
                },
                {
                    "employeeId": 2,
                    "name": "Employee 2 of Dep 2"
                },
                {
                    "employeeId": 3,
                    "name": "Employee 3 of Dep 2"
                },
                {
                    "employeeId": 4,
                    "name": "Employee 4 of Dep 2"
                }
            ]
        },
        {
            "departmentId": 3,
            "name": "Department 3",
            "employees": [
                {
                    "employeeId": 1,
                    "name": "Employee 1 of Dep 3"
                },
                {
                    "employeeId": 2,
                    "name": "Employee 2 of Dep 3"
                },
                {
                    "employeeId": 3,
                    "name": "Employee 3 of Dep 3"
                },
                {
                    "employeeId": 4,
                    "name": "Employee 4 of Dep 3"
                }
            ]
        }
    ]
}

到此这篇关于C++ 使用RapidJson 写入文件的文章就介绍到这了,更多相关C++ 写入文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • C++实现查找二叉树中和为某一值的所有路径的示例

    C++实现查找二叉树中和为某一值的所有路径的示例

    这篇文章主要介绍了C++实现查找二叉树中和为某一值的所有路径的示例,文中的方法是根据数组生成二叉排序树并进行遍历,需要的朋友可以参考下
    2016-02-02
  • Opencv分水岭算法学习

    Opencv分水岭算法学习

    这篇文章主要为大家详细介绍了Opencv分水岭算法的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-01-01
  • C++中给二维指针分配内存(实现代码)

    C++中给二维指针分配内存(实现代码)

    我们都知道在 C++ 中分配动态数组用的是 new , 撤销动态数组用的是 delete[ ] ,现在让我们来看看怎么利用这两个关键字给二维指针分配内存
    2013-10-10
  • C++using声明和using编译指令

    C++using声明和using编译指令

    这篇文章主要介绍了C++using声明和using编译指令,C++当中提供了两种机制来简化对名称空间中名称的使用。using声明使特定的标识符keys,using编译指令使整个名称空间可用。下面我们就来看看这两种机制的相关资料吧,需要的小伙伴可以参考一下
    2021-12-12
  • C/C++中运算符的优先级、运算符的结合性详解

    C/C++中运算符的优先级、运算符的结合性详解

    这篇文章主要介绍了C/C++中运算符的优先级、运算符的结合性详解的相关资料,需要的朋友可以参考下
    2017-02-02
  • C++中将string类型转化为int类型

    C++中将string类型转化为int类型

    本文主要介绍了C++中将string类型转化为int类型的方法。具有很好的参考价值,下面跟着小编一起来看下吧
    2017-02-02
  • windows系统下C++调用matlab程序的方法详解

    windows系统下C++调用matlab程序的方法详解

    这篇文章主要给大家介绍了关于在windows系统下C++调用matlab程序的方法,文中通过示例代码介绍的非常详细,对大家学习或者使用C++具有一定的参考学习价值,需要的朋友们下面跟着小编来一起学习学习吧。
    2017-08-08
  • C语言实现简易扫雷程序

    C语言实现简易扫雷程序

    这篇文章主要为大家详细介绍了C语言实现简易扫雷程序,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • C语言入门篇--定义宏#define的概述

    C语言入门篇--定义宏#define的概述

    本篇文章是C语言系列基础篇,适合c语言刚入门的朋友,本文对关于c语言的定义宏#define作了简要的概述,希望可以帮助大家快速入门c语言的世界,更好的理解c语言
    2021-08-08
  • C语言 小游戏打砖块实现流程详解

    C语言 小游戏打砖块实现流程详解

    打砖块游戏是一种动作电子游戏的名称。玩家操作一根萤幕上水平的“棒子”,让一颗不断弹来弹去的“球”在撞击作为过关目标消去的“砖块”的途中不会落到萤幕底下。球碰到砖块、棒子与底下以外的三边会反弹,落到底下会失去一颗球,把砖块全部消去就可以破关
    2021-11-11

最新评论