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

   2024-09-30 6690
核心提示:在 C++ 中,处理 JSON 数据的常用库有 nlohmann/json 和 RapidJSON。这里我们以 nlohmann/json 为例,介绍如何进行 JSON 数据的

在 C++ 中,处理 JSON 数据的常用库有 nlohmann/json 和 RapidJSON。这里我们以 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 数据序列化的方法。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号