推荐使用nlohmann/json、RapidJSON或JsonCpp解析C++ JSON字符串:nlohmann/json语法简洁适合现代C++;RapidJSON性能高适用于高性能场景;JsonCpp稳定适用于传统项目。

在C++中解析JSON字符串,由于标准库不直接支持JSON处理,通常需要借助第三方库来完成。以下是几种常用且高效的C++ JSON解析方法,适合不同项目需求。
使用nlohmann/json(现代C++推荐)
nlohmann/json 是一个广泛使用的单头文件库,语法简洁,支持C++11及以上版本,非常适合现代C++项目。
使用步骤:- 从GitHub获取头文件或将库集成到项目中(如通过vcpkg或conan)
- 包含头文件:
#include <nlohmann/json.hpp> - 使用
json::parse()解析字符串
示例代码:
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
std::string json_str = R"({"name": "Alice", "age": 25, "city": "Beijing"})";
try {
json j = json::parse(json_str);
std::cout << "Name: " << j["name"] << "\n";
std::cout << "Age: " << j["age"] << "\n";
} catch (const std::exception& e) {
std::cerr << "Parse error: " << e.what() << "\n";
}
return 0;
}
使用RapidJSON(高性能场景)
RapidJSON 是腾讯开源的C++ JSON库,特点是无依赖、速度快,适用于对性能要求高的项目。
立即学习“C++免费学习笔记(深入)”;
特点:- 支持SAX和DOM两种解析模式
- 内存占用低,解析速度快
- 需手动管理类型检查
示例代码:
#include <iostream>
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
int main() {
std::string json_str = R"({"product": "laptop", "price": 5999})";
Document doc;
doc.Parse(json_str.c_str());
if (!doc.HasParseError() && doc.IsObject()) {
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";
}
}
return 0;
}
使用JsonCpp(老牌稳定库)
JsonCpp 是较早出现的C++ JSON库,结构清晰,适合传统项目或嵌入式环境。
使用方式:- 安装JsonCpp(apt、vcpkg或源码编译)
- 包含头文件并链接库
- 用
Json::Reader(旧版)或Json::CharReader(新版)解析
示例代码:
#include <iostream>
#include <json/json.h>
#include <sstream>
int main() {
std::string json_str = R"({"status": "ok", "count": 10})";
Json::Value root;
Json::CharReaderBuilder builder;
std::string errors;
std::istringstream ss(json_str);
if (parseFromStream(builder, ss, &root, &errors)) {
std::cout << "Status: " << root["status"].asString() << "\n";
std::cout << "Count: " << root["count"].asInt() << "\n";
} else {
std::cerr << "Parse failed: " << errors << "\n";
}
return 0;
}
基本上就这些主流方法。选择哪个库取决于你的项目需求:追求简洁用nlohmann/json,追求速度用RapidJSON,维护老项目可用JsonCpp。集成时注意异常处理和类型校验,避免运行时崩溃。











