c++

C++中jason数据的序列化方法

小樊
81
2024-09-14 10:29:47
栏目: 编程语言

在 C++ 中,处理 JSON 数据的常用库有 nlohmann/jsonRapidJSON。这里我们以 nlohmann/json 为例,介绍如何进行 JSON 数据的序列化。

首先,你需要安装 nlohmann/json 库。可以通过包管理器(如 vcpkg)或直接从 GitHub 上克隆并安装。

安装完成后,在代码中包含头文件 nlohmann/json.hpp

#include<iostream>
#include <fstream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;
using namespace std;

接下来,创建一个 JSON 对象并添加数据:

int main() {
    // 创建一个 JSON 对象
    json j;

    // 向 JSON 对象中添加数据
    j["name"] = "John";
    j["age"] = 30;
    j["isStudent"] = false;
    j["courses"] = {"Math", "Physics", "Computer Science"};

    // 输出 JSON 对象
    cout << j.dump(4)<< endl;

    return 0;
}

在这个示例中,我们创建了一个名为 j 的 JSON 对象,并向其中添加了一些键值对。然后使用 dump() 函数将 JSON 对象转换为格式化的字符串并输出。dump() 函数的参数表示缩进的空格数,这里设置为 4。

运行此程序,你将看到以下输出:

{
    "age": 30,
    "courses": [
        "Math",
        "Physics",
        "Computer Science"
    ],
    "isStudent": false,
    "name": "John"
}

这就是在 C++ 中使用 nlohmann/json 库进行 JSON 数据序列化的方法。

0
看了该问题的人还看了