nlohmann/json安装与使用

介绍

nlohmann/json 是一个用于处理 JSON 数据的 C++ 库,提供了简单而强大的 JSON 解析和生成功能。以其简洁易用、功能强大而受到广泛欢迎。

优点

  1. 简单易用:

    • 使用现代 C++ 特性,如自动类型推断和范围 for 循环,简化了 JSON 的创建、访问和操作。
  2. 与标准库兼容:

    • 它与 C++ 标准库兼容,能够方便地与 std::map、std::vector 等 STL 容器一起使用。
  3. 支持多种 JSON 数据类型:

    • 支持 JSON 对象、数组、字符串、数字、布尔值和 null 类型。
  4. 可读性和可维护性:

    • 提供了清晰的 API,使 JSON 数据的操作和读取更加直观和易于理解。
  5. JSON 序列化和反序列化:

    • 可以将 C++ 对象序列化为 JSON 格式,也可以将 JSON 数据反序列化为 C++ 对象。
  6. 异常处理:

    • 提供了友好的异常处理机制,可以处理 JSON 解析错误或类型错误等。

安装

下载源码

地址: https://github.com/nlohmann/json

linux

git clone --branch=v3.11.3 --single-branch --depth=1 https://github.com/nlohmann/json.git
mkdir build
cd build
cmake ..
make
sudo make install

安装在默认路径下/usr/local/include/nlohmann

windows

将nlohmann的头文件包含进项目工程就好了.

使用

基本用法

创建和操作 JSON 对象

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

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

int main() {
    // 创建 JSON 对象
    json j = {
        {"name", "John Doe"},
        {"age", 30},
        {"is_student", false},
        {"courses", {"Math", "Science"}}
    };

    // 访问和修改 JSON 对象
    cout << "Name: " << j["name"] << endl;
    cout << "Age: " << j["age"] << endl;
    j["age"] = 31;  // 修改年龄

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

    return 0;
}

解析 JSON 字符串

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

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

int main() {
    string json_str = R"({"name": "Jane Doe", "age": 25, "is_student": true})";
    json j = json::parse(json_str);

    cout << "Name: " << j["name"] << endl;
    cout << "Age: " << j["age"] << endl;
    cout << "Is student: " << (j["is_student"] ? "Yes" : "No") << endl;

    return 0;
}

与 std::map 一起使用

从 std::map 创建 JSON 对象

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

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

int main() {
    // 创建 std::map
    map<string, int> data = {
        {"Alice", 30},
        {"Bob", 25},
        {"Charlie", 35}
    };

    // 将 std::map 转换为 JSON 对象
    json j = data;

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

    return 0;
}

从 JSON 对象创建 std::map

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

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

int main() {
    // 创建 JSON 对象
    json j = {
        {"Alice", 30},
        {"Bob", 25},
        {"Charlie", 35}
    };

    // 从 JSON 对象转换为 std::map
    map<string, int> data = j.get<map<string, int>>();

    // 输出 std::map
    for (const auto& [key, value] : data) {
        cout << key << ": " << value << endl;
    }

    return 0;
}

与 std::vector 一起使用

从 std::vector 创建 JSON 数组

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

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

int main() {
    // 创建 std::vector
    vector<int> numbers = {1, 2, 3, 4, 5};

    // 将 std::vector 转换为 JSON 数组
    json j = numbers;

    // 输出 JSON 数组
    cout << j.dump(4) << endl;

    return 0;
}

从 JSON 数组创建 std::vector

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

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

int main() {
    // 创建 JSON 数组
    json j = {1, 2, 3, 4, 5};

    // 从 JSON 数组转换为 std::vector
    vector<int> numbers = j.get<vector<int>>();

    // 输出 std::vector
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

复杂的数据结构

#include <iostream>
#include <nlohmann/json.hpp>
#include <vector>
#include <map>

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

int main() {
    // 创建嵌套数据结构
    map<string, vector<int>> data = {
        {"group1", {1, 2, 3}},
        {"group2", {4, 5, 6}}
    };

    // 将 std::map 和 std::vector 转换为 JSON 对象
    json j = data;

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

    // 从 JSON 对象创建 std::map
    map<string, vector<int>> new_data = j.get<map<string, vector<int>>>();

    // 输出新创建的 std::map
    for (const auto& [key, value] : new_data) {
        cout << key << ": ";
        for (int num : value) {
            cout << num << " ";
        }
        cout << endl;
    }

    return 0;
}

通过 nlohmann/json,可以很方便地将 STL 容器与 JSON 数据互转。这使得在 C++ 中处理 JSON 数据变得更加自然,允许你轻松地利用 STL 容器的强大功能。

自定义对象

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

// 需要序列化的类
class Person {
public:
    std::string name;
    int age;

    // 序列化
    NLOHMANN_DEFINE_TYPE_INTRUSIVE(Person, name, age)
};

int main() {
    // 创建一个 Person 对象
    Person person;
    person.name = "Alice";
    person.age = 30;

    // 将 Person 对象序列化为 JSON
    nlohmann::json j = person;
    std::cout << "Serialized JSON: " << j << std::endl;

    // 反序列化 JSON 为 Person 对象
    Person deserializedPerson = j.get<Person>();
    std::cout << "Deserialized Person - Name: " << deserializedPerson.name
              << ", Age: " << deserializedPerson.age << std::endl;

    return 0;
}

结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值