nlohmann/json 是C++中处理JSON的常用库,只需包含json.hpp头文件即可使用,支持C++11及以上版本,提供简洁语法进行JSON解析、生成和操作。

在C++中处理JSON数据时,nlohmann/json 是一个非常流行且易用的开源库。它不依赖外部库,只需包含头文件即可使用,支持现代C++语法(如C++11及以上),能轻松实现JSON的解析、生成和操作。
安装与配置 nlohmann/json
最简单的方式是通过单个头文件引入:
- 从GitHub下载最新版本:https://www.php.cn/link/b82e68e6366d4177332acdf3fa4d1e3a
- 将 json.hpp 文件放入项目include目录
- 在代码中包含:#include
如果你使用的是包管理工具:
- vcpkg: vcpkg install nlohmann-json
- conan: 添加 nlohmann_json/3.11.2 到依赖
- Linux (Ubuntu): sudo apt install nlohmann-json3-dev
基本 JSON 解析示例
假设有一个JSON字符串:
立即学习“C++免费学习笔记(深入)”;
std::string json_str = R"({
"name": "Alice",
"age": 25,
"is_student": false,
"hobbies": ["reading", "coding"],
"address": {
"city": "Beijing",
"zipcode": "100001"
}
})";
使用nlohmann/json解析并访问字段:
#include#include using json = nlohmann::json; int main() { std::string json_str = R"({"name": "Alice", "age": 25, ... })"; 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; } // 对象嵌套 std::cout << "City: " << j["address"]["city"] << std::endl; } catch (const json::parse_error& e) { std::cerr << "Parse error: " << e.what() << std::endl; } return 0; }
序列化(对象转JSON)
可以反过来将C++变量构造成JSON对象:
json j;
j["name"] = "Bob";
j["score"] = 95.5;
j["tags"] = {"cpp", "json", "programming"};
j["meta"]["version"] = "1.0";
j["meta"]["active"] = true;
std::string output = j.dump(2); // 格式化缩进为2空格
std::cout << output << std::endl;
输出结果:
{
"meta": {
"active": true,
"version": "1.0"
},
"name": "Bob",
"score": 95.5,
"tags": ["cpp", "json", "programming"]
}
结构体与JSON映射(自定义类型序列化)
可以通过定义 to_json 和 from_json 函数实现结构体与JSON互转:
struct Person {
std::string name;
int age;
bool is_student;
};
void to_json(json& j, const Person& p) {
j = json{{"name", p.name}, {"age", p.age}, {"is_student", p.is_student}};
}
void from_json(const json& j, Person& p) {
j.at("name").get_to(p.name);
j.at("age").get_to(p.age);
j.at("is_student").get_to(p.is_student);
}
使用方式:
Person p = {"Tom", 20, true};
json j = p; // 自动调用 to_json
std::cout << j.dump(2) << std::endl;
// 反向解析
Person p2 = j.get(); // 自动调用 from_json
基本上就这些常用操作。nlohmann/json语法直观,兼容STL容器,适合快速开发中处理配置、网络接口数据等场景。只要记得捕获异常、检查键是否存在,就能安全高效地使用。










