C++中解析JSON需借助第三方库,常用jsoncpp和nlohmann/json。1. jsoncpp需安装libjsoncpp-dev并链接-ljsoncpp,通过Json::Value解析文件,适用于稳定大型项目;2. nlohmann/json为头文件-only库,只需包含json.hpp,语法简洁,支持现代C++特性,适合新项目;两者均需处理文件存在性与JSON格式错误,推荐使用try-catch捕获异常,确保程序健壮性。

在C++中解析JSON数据,由于标准库没有内置支持,通常需要借助第三方库来完成。目前最常用且易用的库是 jsoncpp 和 nlohmann/json(也叫 JSON for Modern C++)。下面分别介绍这两种方法如何读取和解析JSON文件。
使用 jsoncpp 解析 JSON 文件
jsoncpp 是一个成熟、轻量的C++库,适合处理结构化的JSON数据。
步骤如下:1. 安装 jsoncpp
在Ubuntu上可通过命令安装:
sudo apt-get install libjsoncpp-dev
编译时需链接库:-ljsoncpp
立即学习“C++免费学习笔记(深入)”;
2. 示例代码:读取并解析 JSON 文件
#include
#include
#include
int main() {
std::ifstream file("data.json");
Json::Value root;
Json::CharReaderBuilder builder;
std::string errs;
if (!parseFromStream(builder, file, &root, &errs)) {
std::cerr << "解析失败: " << errs << std::endl;
return 1;
}
// 读取字段
std::string name = root["name"].asString();
int age = root["age"].asInt();
bool isStudent = root["is_student"].asBool();
std::cout << "姓名: " << name << std::endl;
std::cout << "年龄: " << age << std::endl;
std::cout << "是否学生: " << (isStudent ? "是" : "否") << std::endl;
// 遍历数组
const Json::Value hobbies = root["hobbies"];
for (const auto& hobby : hobbies) {
std::cout << "爱好: " << hobby.asString() << std::endl;
}
return 0;
}
对应的 data.json 内容示例:
{
"name": "张三",
"age": 20,
"is_student": true,
"hobbies": ["读书", "游泳", "编程"]
}
使用 nlohmann/json 解析 JSON
nlohmann/json 是现代C++中非常流行的头文件-only库,语法简洁直观,推荐用于新项目。
1. 获取库
下载单头文件版本 json.hpp,从 GitHub:https://www.php.cn/link/b82e68e6366d4177332acdf3fa4d1e3a
将 json.hpp 放入项目目录,无需编译。
2. 示例代码
#include
#include
#include
#include "json.hpp"
using json = nlohmann::json;
int main() {
std::ifstream file("data.json");
json j;
file >> j;
// 读取数据
std::string name = j["name"];
int age = j["age"];
bool isStudent = j["is_student"];
std::cout << "姓名: " << name << std::endl;
std::cout << "年龄: " << age << std::endl;
std::cout << "是否学生: " << (isStudent ? "是" : "否") << std::endl;
// 遍历数组
for (const auto& hobby : j["hobbies"]) {
std::cout << "爱好: " << hobby << std::endl;
}
return 0;
}
编译时只需包含头文件路径,不需要额外链接库。
选择建议与注意事项
两种方式各有优势:
- jsoncpp 更适合大型项目或已有CMake集成环境,稳定性高。
- nlohmann/json 使用更简洁,支持现代C++特性,开发效率高,适合新项目。
注意检查文件是否存在、JSON格式是否正确,避免运行时崩溃。可以加 try-catch 处理异常,尤其是 nlohmann/json 在访问不存在的键时可能抛出异常。
基本上就这些。根据项目需求选一个合适的库,就能轻松实现C++中JSON的读取与解析。











