信息发布→ 登录 注册 退出

c++中如何解析JSON字符串_c++ JSON解析方法与示例

发布时间:2025-11-15

点击量:
C++中解析JSON需借助第三方库,常用的是jsoncpp和nlohmann/json。1. jsoncpp轻量跨平台,通过Json::Reader解析字符串,需安装libjsoncpp-dev并链接-ljsoncpp;示例代码展示从JSON字符串提取name、age、city字段。2. nlohmann/json为单头文件库,支持现代C++语法,只需包含json.hpp即可使用,通过json::parse()解析,支持异常处理;示例包括解析基本类型及数组(如hobbies)。3. 对嵌套结构(如user.profile.name),nlohmann/json可通过链式下标访问,代码简洁。4. 推荐:传统项目用jsoncpp,现代C++项目优选nlohmann/json,性能敏感场景可选rapidjson。解析前应验证JSON格式,并使用try-catch捕获异常,确保健壮性。

在C++中解析JSON字符串,由于标准库不直接支持JSON操作,通常需要借助第三方库来完成。目前最常用且易于使用的库是 jsoncppnlohmann/json(也称JSON for Modern C++)。下面分别介绍这两种方法,并提供具体示例。

使用 jsoncpp 解析 JSON 字符串

jsoncpp 是一个轻量级、跨平台的C++库,专门用于处理JSON数据。它提供了简单的API来解析和生成JSON。

安装 jsoncpp(Ubuntu/Debian):

sudo apt-get install libjsoncpp-dev

编译时链接库:

g++ main.cpp -ljsoncpp -o parse_json

示例代码:

#include 
#include 
#include 

int main() {
    std::string json_str = R"({"name": "Alice", "age": 25, "city": "Beijing"})";

    Json::Value root;
    Json::Reader reader;

    std::istringstream iss(json_str);
    bool parsingSuccessful = reader.parse(iss, root);
    if (!parsingSuccessful) {
        std::cout << "Failed to parse JSON: " << reader.getFormattedErrorMessages();
        return 1;
    }

    std::string name = root["name"].asString();
    int age = root["age"].asInt();
    std::string city = root["city"].asString();

    std::cout << "Name: " << name << "\n";
    std::cout << "Age: " << age << "\n";
    std::cout << "City: " << city << "\n";

    return 0;
}

使用 nlohmann/json 解析 JSON 字符串

nlohmann/json 是一个单头文件库,使用现代C++语法,接口简洁直观,广泛用于C++11及以上项目。

获取方式:

  • 从 GitHub 下载:https://github.com/nlohmann/json
  • single_include/nlohmann/json.hpp 添加到项目中即可使用

示例代码:

#include 
#include 
#include "json.hpp"

using json = nlohmann::json;

int main() {
    std::string json_str = R"({"name": "Bob", "age": 30, "hobbies": ["reading", "coding"]})";

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

        std::string name = j["name"];
        int age = j["age"];
        auto hobbies = j["hobbies"];

        std::cout << "Name: " << name << "\n";
        std::cout << "Age: " << age << "\n";
        std::cout << "Hobbies: ";
        for (const auto& h : hobbies) {
            std::cout << h << " ";
        }
        std::cout << "\n";
    } catch (const std::exception& e) {
        std::cerr << "JSON parse error: " << e.what() << "\n";
    }

    return 0;
}

处理嵌套 JSON 示例

对于包含对象或数组嵌套的复杂结构,两种库都能轻松应对。

使用 nlohmann/json 处理嵌套对象:

std::string complex_json = R"({
    "user": {
        "id": 1001,
        "profile": {
            "name": "Charlie",
            "email": "charlie@example.com"
        }
    },
    "active": true
})";

json j = json::parse(complex_json);
std::string name = j["user"]["profile"]["name"];
int user_id = j["user"]["id"];
bool active = j["active"];

std::cout << "User: " << name << ", ID: " << user_id << ", Active: " << active << "\n";

择建议与注意事项

  • 若项目允许引入外部依赖,jsoncpp 更适合传统C++项目,系统包管理器支持好
  • nlohmann/json 更适合现代C++项目,集成简单,语法更自然,推荐新项目使用
  • 解析前应确保JSON字符串格式正确,建议用 try-catch 捕获解析异常
  • 对于性能敏感场景,可考虑 rapidjson,但API相对复杂
基本上就这些。根据项目需求选择合适库,能快速实现JSON解析功能。
标签:# 接口  # 只需  # 两种  # 都能  # 头文件  # 的是  # 前应  # 更适合  # 第三方  # 链式  # 是一个  # debian  # https  # 对象  # js  # 字符串  # catch  # try  # for  # 标准库  # stream  # ios  # c++  # ai  # ubuntu  # github  # json  # git  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!