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

在C++中处理JSON数据时,nlohmann/json 是一个非常流行且易用的开源库。它不依赖外部库,只需包含头文件即可使用,支持现代C++语法(如C++11及以上),能轻松实现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解析并访问字段:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
#include <iostream>
#include <json.hpp>
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;
}
可以反过来将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"]
}
可以通过定义 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<Person>(); // 自动调用 from_json
基本上就这些常用操作。nlohmann/json语法直观,兼容STL容器,适合快速开发中处理配置、网络接口数据等场景。只要记得捕获异常、检查键是否存在,就能安全高效地使用。
以上就是C++如何使用nlohmann/json库解析JSON_C++ JSON处理库nlohmann/json使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号