推荐使用nlohmann/json解析C++ JSON数据,因其语法简洁且易于集成;也可根据需求选择RapidJSON(高性能)或JsonCpp(传统项目),三者均需引入第三方库并注意错误处理。
在C++中解析JSON数据,由于标准库不直接支持JSON,通常需要借助第三方库来实现。以下是几种常用且高效的C++ JSON解析方法,适合不同项目需求。
使用nlohmann/json(推荐)
nlohmann/json 是一个广泛使用的单头文件库,语法简洁,易于集成,非常适合现代C++项目。
使用步骤:
- 从GitHub下载或通过包管理器安装(如vcpkg、conan)。
- 包含头文件:#include <nlohmann/json.hpp>
- 使用
json::parse()
解析字符串。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream> #include <nlohmann/json.hpp> <p>using json = nlohmann::json;</p><p>int main() { std::string data = R"({"name": "Alice", "age": 25, "city": "Beijing"})"; json j = json::parse(data);</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">std::cout << "Name: " << j["name"] << "n"; std::cout << "Age: " << j["age"] << "n"; if (j.contains("city")) { std::cout << "City: " << j["city"] << "n"; }
}
使用RapidJSON
RapidJSON 是腾讯开发的高性能C++ JSON库,支持SAX和DOM解析,内存占用低,适合对性能要求高的场景。
特点:

Find JSON Path Online
30
Easily find JSON paths within JSON objects using our intuitive Json Path Finder

- 无需依赖,纯C++实现。
- 支持流式解析,速度快。
- 需手动处理类型检查。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream> #include "rapidjson/document.h" #include "rapidjson/stringbuffer.h" <p>using namespace rapidjson;</p><p>int main() { const char* json_str = R"({"product": "laptop", "price": 5999})"; Document doc; doc.Parse(json_str);</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">if (doc.HasMember("product") && doc["product"].IsString()) { std::cout << "Product: " << doc["product"].GetString() << "n"; } if (doc.HasMember("price") && doc["price"].IsNumber()) { std::cout << "Price: " << doc["price"].GetInt() << "n"; }
}
使用JsonCpp
JsonCpp 是较早流行的C++ JSON库,API清晰,适合传统项目。
使用方法:
- 安装JsonCpp库(apt、brew或编译源码)。
- 包含<json/json.h>。
- 用
Json::Reader
解析(旧版)或Json::CharReader
(新版)。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream> #include <json/json.h> #include <sstream> <p>int main() { std::string data = R"({"status": "ok", "count": 10})"; Json::Value root; Json::CharReaderBuilder builder; std::string errs;</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">std::istringstream iss(data); if (Json::parseFromStream(builder, iss, &root, &errs)) { std::cout << "Status: " << root["status"].asString() << "n"; std::cout << "Count: " << root["count"].asInt() << "n"; } else { std::cout << "Parse error: " << errs << "n"; }
}
基本上就这些。选择哪个库取决于项目需求:nlohmann/json适合现代C++开发,RapidJSON适合高性能场景,JsonCpp适合维护老项目。引入对应库后,解析JSON就是读取键值、判断类型、提取数据的过程,不复杂但容易忽略错误处理。
js git json github 腾讯 ai c++ ios stream 内存占用 c++开发 标准库 json include 字符串 dom github