首页 > 后端开发 > C++ > 正文

c++怎么解析json字符串_json字符串解析库使用

裘德小鎮的故事
发布: 2025-09-26 18:34:01
原创
497人浏览过
c++kquote>解析JSON需借助第三方库,常用库有nlohmann/json、JsonCpp和rapidjson;nlohmann语法简洁适合现代C++,JsonCpp兼容性好,rapidjson性能高;示例展示了各库的基本解析方法及错误处理。

c++怎么解析json字符串_json字符串解析库使用

解析 JSON 字符串在 C++ 中是一个常见需求,尤其是在处理网络请求、配置文件或前后端数据交互时。由于 C++ 标准库不直接支持 JSON 解析,通常需要借助第三方库来完成。下面介绍几种常用的 C++ JSON 解析库及其基本使用方法。

常用 C++ JSON 解析库

以下是几个广泛使用且维护良好的 C++ JSON 库:

  • nlohmann/json:现代 C++(C++11 及以上)风格,头文件仅需包含一个头文件,使用方便。
  • JsonCpp:老牌库,功能稳定,支持老版本 C++,适合项目兼容性要求高的场景。
  • rapidjson:性能高,内存占用低,适合对性能敏感的应用。

nlohmann/json 使用示例

这个库以简洁的语法著称,推荐用于现代 C++ 项目。

// 安装方式:通过 vcpkg、conan 或直接下载 single_include 版本

使用步骤:

立即学习C++免费学习笔记(深入)”;

  • 下载 nlohmann json 的单头文件版本(json.hpp)并包含到项目中。
  • 在代码中包含头文件并开始解析。

示例代码:

阿里云-虚拟数字人
阿里云-虚拟数字人

阿里云-虚拟数字人是什么? ...

阿里云-虚拟数字人2
查看详情 阿里云-虚拟数字人
#include <iostream>
#include <string>
#include "nlohmann/json.hpp"

using json = nlohmann::json;

int main() {
    std::string json_str = R"({
        "name": "Tom",
        "age": 25,
        "is_student": false,
        "hobbies": ["reading", "gaming"]
    })";

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

        std::cout << "Name: " << j["name"] << std::endl;
        std::cout << "Age: " << j["age"] << std::endl;
        std::cout << "Is student: " << std::boolalpha << j["is_student"] << std::endl;

        for (const auto& hobby : j["hobbies"]) {
            std::cout << "Hobby: " << hobby << std::endl;
        }
    } catch (const std::exception& e) {
        std::cerr << "JSON parse error: " << e.what() << std::endl;
    }

    return 0;
}
登录后复制

编译时确保启用 C++11 或更高标准:
g++ -std=c++11 main.cpp -o main

JsonCpp 使用示例

JsonCpp 是较早出现的库,API 稍显传统但稳定。

  • 安装:可通过包管理器安装,如 apt install libjsoncpp-dev(Linux)或使用 CMake 引入。
  • 包含头文件并链接库。

示例代码:

#include <iostream>
#include <string>
#include <json/json.h>

int main() {
    std::string json_str = R"({
        "name": "Alice",
        "score": 95.5
    })";

    Json::Value root;
    Json::CharReaderBuilder builder;
    std::string errs;

    const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
    if (!reader->parse(json_str.c_str(), json_str.c_str() + json_str.size(), &root, &errs)) {
        std::cerr << "Parse error: " << errs << std::endl;
        return -1;
    }

    std::cout << "Name: " << root["name"].asString() << std::endl;
    std::cout << "Score: " << root["score"].asDouble() << std::endl;

    return 0;
}
登录后复制

编译命令(需链接 JsonCpp 库):
g++ main.cpp -ljsoncpp -o main

rapidjson 使用示例

rapidjson 以高性能和零依赖著称,适合嵌入式或性能关键系统。

  • 下载 rapidjson 源码并包含 include 目录。
  • 直接包含头文件使用。

示例代码:

#include <iostream>
#include <string>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"

using namespace rapidjson;

int main() {
    std::string json_str = R"({"user":"Bob","active":true})";

    Document doc;
    doc.Parse(json_str.c_str());

    if (doc.HasParseError()) {
        std::cerr << "Parse error" << std::endl;
        return -1;
    }

    if (doc.HasMember("user") && doc["user"].IsString()) {
        std::cout << "User: " << doc["user"].GetString() << std::endl;
    }

    if (doc["active"].IsBool()) {
        std::cout << "Active: " << (doc["active"].GetBool() ? "yes" : "no") << std::endl;
    }

    return 0;
}
登录后复制

基本上就这些。选择哪个库取决于你的项目需求:追求简洁用 nlohmann/json,追求性能用 rapidjson,需要兼容旧项目可用 JsonCpp。集成时注意异常处理和字符串合法性检查,避免运行时崩溃。不复杂但容易忽略。

以上就是c++++怎么解析json字符串_json字符串解析库使用的详细内容,更多请关注php中文网其它相关文章!

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号