Linux下C++的JSON解析

发布时间:2024-12-20 09:49:52 作者:小樊
来源:亿速云 阅读:108

在 Linux 下,有许多 C++ 库可以用来解析 JSON 数据

  1. nlohmann/json

nlohmann/json 是一个广泛使用的 C++ JSON 库,它的 GitHub 仓库地址为:https://github.com/nlohmann/json

要使用这个库,首先需要将其添加到你的项目中。如果你使用的是 CMake,可以在你的 CMakeLists.txt 文件中添加以下代码:

add_subdirectory(nlohmann-json)
include_directories(${nlohmann_json_SOURCE_DIR}/include)

然后,你可以在你的 C++ 文件中包含 nlohmann/json.hpp 头文件并使用它来解析 JSON 数据:

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

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

int main() {
    string json_str = R"(
    {
        "name": "John",
        "age": 30,
        "city": "New York"
    }
    )"_json; // 注意 _json 后缀

    json j = json::parse(json_str);

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

    return 0;
}
  1. rapidjson

rapidjson 是一个高性能的 C++ JSON 库,它的 GitHub 仓库地址为:https://github.com/Tencent/rapidjson

要使用这个库,首先需要将其添加到你的项目中。如果你使用的是 CMake,可以在你的 CMakeLists.txt 文件中添加以下代码:

add_subdirectory(rapidjson)
include_directories(${RapidJSON_SOURCE_DIR}/include)

然后,你可以在你的 C++ 文件中包含 rapidjson/document.h 头文件并使用它来解析 JSON 数据:

#include <iostream>
#include <rapidjson/document.h>

using namespace rapidjson;
using namespace std;

int main() {
    const char* json_str = R"(
    {
        "name": "John",
        "age": 30,
        "city": "New York"
    }
    )";

    Document d;
    d.Parse(json_str);

    cout << "Name: " << d["name"].GetString() << endl;
    cout << "Age: " << d["age"].GetInt() << endl;
    cout << "City: " << d["city"].GetString() << endl;

    return 0;
}

这两个库都有很好的文档和社区支持,你可以根据自己的需求选择合适的库来解析 JSON 数据。

推荐阅读:
  1. linux中vim使用技巧有哪些
  2. linux搭建maven环境

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

linux

上一篇:Linux开发C++的自动化部署方法

下一篇:C++在Linux中的图像处理

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》