nlohmann/json是C++中处理JSON的流行头文件库,支持通过vcpkg、Conan或直接引入json.hpp安装,可便捷解析字符串、文件等来源的JSON数据,语法简洁易用。

在C++中处理JSON数据,nlohmann/json 是目前最流行、使用最广泛的第三方库之一。它提供了简洁直观的API,让开发者可以像操作JavaScript对象一样读写JSON,极大简化了JSON解析与生成的过程。
nlohmann/json 是一个头文件-only 的库,意味着你不需要编译或链接额外的二进制文件,只需包含头文件即可使用。
方法一:通过 vcpkg 或 conan 包管理器安装(推荐)vcpkg install nlohmann-jsonrequires: nlohmann_json/3.11.2
json.hpp 文件:https://www.php.cn/link/b82e68e6366d4177332acdf3fa4d1e3a
#include "json.hpp"使用 nlohmann/json 解析 JSON 字符串非常简单,支持从字符串、文件、标准输入等多种方式读取。
示例:解析 JSON 字符串#include <iostream>
#include <string>
#include "json.hpp"
using json = nlohmann::json;
int main() {
std::string json_str = R"({
"name": "Alice",
"age": 25,
"is_student": false,
"hobbies": ["reading", "coding"],
"address": {
"city": "Beijing",
"zipcode": "100001"
}
})";
try {
json j = json::parse(json_str);
std::cout << "Name: " << j["name"] << std::endl;
std::cout << "Age: " << j["age"] << std::endl;
std::cout << "City: " << j["address"]["city"] << std::endl;
// 遍历数组
for (const auto& hobby : j["hobbies"]) {
std::cout << "Hobby: " << hobby << std::endl;
}
} catch (const std::exception& e) {
std::cerr << "Parse error: " << e.what() << std::endl;
}
return 0;
}
注意:访问不存在的键会抛出异常,建议使用 contains() 判断或 find() 方法安全访问。
立即学习“C++免费学习笔记(深入)”;
构造 JSON 对象就像使用 map 和 list 一样自然。
示例:构建并输出 JSONjson j;
j["name"] = "Bob";
j["age"] = 30;
j["is_student"] = true;
j["hobbies"] = {"gaming", "music"};
j["score"] = 95.5;
// 构造嵌套对象
j["address"]["city"] = "Shanghai";
j["address"]["zipcode"] = "200000";
// 输出格式化 JSON
std::cout << j.dump(4) << std::endl; // 参数 4 表示缩进 4 个空格
dump() 方法可将 JSON 对象序列化为字符串,常用于网络传输或保存到文件。
可以通过定义 to_json() 和 from_json() 函数实现结构体与 JSON 的自动转换。
struct Person {
std::string name;
int age;
std::vector<std::string> hobbies;
};
void to_json(json& j, const Person& p) {
j = json{{"name", p.name}, {"age", p.age}, {"hobbies", p.hobbies}};
}
void from_json(const json& j, Person& p) {
j.at("name").get_to(p.name);
j.at("age").get_to(p.age);
j.at("hobbies").get_to(p.hobbies);
}
使用示例:
Person p = {"Tom", 22, {"basketball", "swimming"}};
json j = p; // 自动调用 to_json
std::cout << j.dump(2) << std::endl;
Person p2 = j.get<Person>(); // 自动调用 from_json
这种方式让数据序列化变得非常清晰和类型安全。
基本上就这些。nlohmann/json 设计优雅,文档完善,是 C++ 中处理 JSON 的首选方案。只要包含一个头文件,就能轻松完成解析、生成、嵌套、序列化等操作,适合各种中小型项目快速开发。
以上就是C++怎么处理JSON数据_C++第三方库nlohmann/json的解析与生成的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号