C++怎么处理JSON数据_C++第三方库nlohmann/json的解析与生成

nlohmann/json是C++中处理JSON的流行头文件库,支持通过vcpkg、Conan或直接引入json.hpp安装,可便捷解析字符串、文件等来源的JSON数据,语法简洁易用。

在C++中处理JSON数据,nlohmann/json 是目前最流行、使用最广泛的第三方库之一。它提供了简洁直观的API,让开发者可以像操作JavaScript对象一样读写JSON,极大简化了JSON解析与生成的过程。

安装与配置 nlohmann/json

nlohmann/json 是一个头文件-only 的库,意味着你不需要编译或链接额外的二进制文件,只需包含头文件即可使用。

方法一:通过 vcpkg 或 conan 包管理器安装(推荐)
  • vcpkg install nlohmann-json
  • 或使用 Conan 添加依赖:requires: nlohmann_json/3.11.2
方法二:直接下载头文件
  • 从 GitHub 下载 json.hpp 文件:https://www./link/b82e68e6366d4177332acdf3fa4d1e3a
  • 将文件放入项目 include 目录,并在代码中包含:
  • #include "json.hpp"

解析 JSON 数据

使用 nlohmann/json 解析 JSON 字符串非常简单,支持从字符串、文件、标准输入等多种方式读取。

示例:解析 JSON 字符串
#include 
#include 
#include "json.hpp"

using json = nlohmann::json;

int main() {
    std::string json_str = R"({
        "name": "Alice",
        "age": 25,
        "is_student": false,
        "hobbies": ["reading", "coding"],
        "address": {
            "city": "Beijing",
            "zipcode": "100001"
        }
    })";

    try {
        json j = json::parse(json_str);

        std::cout << "Name: " << j["name"] << std::endl;
        std::cout << "Age: " << j["age"] << std::endl;
        std::cout << "City: " << j["address"]["city"] << std::endl;

        // 遍历数组
        for (const auto& hobby : j["hobbies"]) {
            std::cout << "Hobby: " << hobby << std::endl;
        }
    } catch (const std::exception& e) {
        std::cerr << "Parse error: " << e.what() << std::endl;
    }

    return 0;
}

注意:访问不存在的键会抛出异常,建议使用 contains() 判断或 find() 方法安全访问。

生成 JSON 数据

构造 JSON 对象就像使用 map 和 list 一样自然。

示例:构建并输出 JSON
json j;
j["name"] = "Bob";
j["age"] = 30;
j["is_student"] = true;
j["hobbies"] = {"gaming", "music"};
j["score"] = 95.5;

// 构造嵌套对象
j["address"]["city"] = "Shanghai";
j["address"]["zipcode"] = "200000";

// 输出格式化 JSON
std::cout << j.dump(4) << std::endl;  // 参数 4 表示缩进 4 个空格

dump() 方法可将 JSON 对象序列化为字符串,常用于网络传输或保存到文件。

与自定义结构体互转

可以通过定义 to_json()from_json() 函数实现结构体与 JSON 的自动转换。

struct Person {
    std::string name;
    int age;
    std::vector hobbies;
};

void to_json(json& j, const Person& p) {
    j = json{{"name", p.name}, {"age", p.age}, {"hobbies", p.hobbies}};
}

void from_json(const json& j, Person& p) {
    j.at("name").get_to(p.name);
    j.at("age").get_to(p.age);
    j.at("hobbies").get_to(p.hobbies);
}

使用示例:

Person p = {"Tom", 22, {"basketball", "swimming"}};
json j = p;  // 自动调用 to_json
std::cout << j.dump(2) << std::endl;

Person p2 = j.get();  // 自动调用 from_json

这种方式让数据序列化变得非常清晰和类型安全。

基本上就这些。nlohmann/json 设计优雅,文档完善,是 C++ 中处理 JSON 的首选方案。只要包含一个头文件,就能轻松完成解析、生成、嵌套、序列化等操作,适合各种中小型项目快速开发。