解析JSON需借助第三方库,常用库有nlohmann/json、JsonCpp和rapidjson;nlohmann语法简洁适合现代C++,JsonCpp兼容性好,rapidjson性能高;示例展示了各库的基本解析方法及错误处理。

解析 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)并包含到项目中。
- 在代码中包含头文件并开始解析。
示例代码:
#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。集成时注意异常处理和字符串合法性检查,避免运行时崩溃。不复杂但容易忽略。











