温馨提示×

C++ request库如何处理JSON数据

c++
小樊
82
2024-09-06 10:16:29
栏目: 编程语言

在C++中,有多种库可以用来处理JSON数据。这里我们将介绍一个流行的库——nlohmann/json。它是一个高性能、易于使用的JSON库,支持序列化和反序列化操作。

首先,你需要安装nlohmann/json库。你可以通过包管理器(如vcpkg)或直接从GitHub下载源代码:https://github.com/nlohmann/json

安装完成后,在你的C++项目中包含头文件#include <nlohmann/json.hpp>

下面是一些基本示例,展示如何使用nlohmann/json库处理JSON数据:

  1. 创建一个JSON对象:
#include<iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

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

    // 向JSON对象添加键值对
    j["name"] = "Alice";
    j["age"] = 30;
    j["is_student"] = false;

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

    return 0;
}
  1. 解析JSON字符串:
#include<iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    // JSON字符串
    std::string json_str = R"({"name": "Bob", "age": 25, "is_student": true})";

    // 解析JSON字符串
    json j = json::parse(json_str);

    // 访问JSON对象的值
    std::string name = j["name"];
    int age = j["age"];
    bool is_student = j["is_student"];

    // 输出结果
    std::cout << "Name: "<< name << ", Age: "<< age << ", Is student: " << (is_student ? "Yes" : "No")<< std::endl;

    return 0;
}
  1. 处理JSON数组:
#include<iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    // JSON数组
    std::string json_str = R"([{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}])";

    // 解析JSON字符串
    json j = json::parse(json_str);

    // 遍历JSON数组
    for (const auto& item : j) {
        std::string name = item["name"];
        int age = item["age"];

        std::cout << "Name: "<< name << ", Age: "<< age<< std::endl;
    }

    return 0;
}

更多关于nlohmann/json库的信息和示例,请参考官方文档:https://nlohmann.github.io/json/

0