在现代 C++ 开发中,处理 JSON 数据是一项常见需求。无论是与 Web API 通信、读取配置文件,还是保存用户数据,nlohmann/json 库都因其简洁、高效和易用性而广受欢迎。本文将带你从零开始,一步步学习如何在 C++ 项目中使用 nlohmann/json 库来解析和生成 JSON 数据。

nlohmann/json 是一个仅需头文件的 C++11 JSON 库,由 Niels Lohmann 开发。它无需编译,只需包含一个头文件即可使用,支持 JSON 的解析、序列化、遍历、修改等操作,并且语法非常接近原生 C++,对初学者极其友好。
该库是开源的,GitHub 上拥有数万颗星,被广泛应用于各类 C++ 项目中,是处理 JSON 数据的首选工具之一。
由于 nlohmann/json 是 header-only(仅头文件)库,安装非常简单:
single_include/nlohmann/json.hpp 文件include/ 文件夹)#include "nlohmann/json.hpp"你也可以通过包管理器安装,比如 vcpkg、Conan 或 CMake FetchContent,但对新手来说,直接下载头文件是最简单的方式。
你可以像使用 STL 容器一样创建和操作 JSON 数据:
#include <iostream>#include "nlohmann/json.hpp"using json = nlohmann::json;int main() { json j; j["name"] = "张三"; j["age"] = 25; j["is_student"] = false; j["hobbies"] = {"读书", "编程", "旅行"}; std::cout << j.dump(4) << std::endl; // 格式化输出,缩进4空格 return 0;}输出结果为格式化的 JSON 字符串:
{ "name": "张三", "age": 25, "is_student": false, "hobbies": [ "读书", "编程", "旅行" ]}从字符串解析 JSON 同样简单:
#include <iostream>#include "nlohmann/json.hpp"using json = nlohmann::json;int main() { std::string text = R"({ "city": "北京", "population": 21540000, "landmarks": ["故宫", "长城", "颐和园"] })"; json j = json::parse(text); std::cout << "城市: " << j["city"] << std::endl; std::cout << "人口: " << j["population"] << std::endl; for (const auto& landmark : j["landmarks"]) { std::cout << "- " << landmark << std::endl; } return 0;}nlohmann/json 支持通过自定义函数实现 C++ 类型与 JSON 的自动转换。例如:
#include <iostream>#include "nlohmann/json.hpp"struct Person { std::string name; int age;};// 定义 to_json 和 from_json 函数void to_json(nlohmann::json& j, const Person& p) { j = nlohmann::json{{"name", p.name}, {"age", p.age}};}void from_json(const nlohmann::json& j, Person& p) { j.at("name").get_to(p.name); j.at("age").get_to(p.age);}int main() { Person p{"李四", 30}; json j = p; // 自动调用 to_json std::cout << j.dump() << std::endl; Person p2 = j.get<Person>(); // 自动调用 from_json std::cout << "姓名: " << p2.name << ", 年龄: " << p2.age << std::endl; return 0;}using json = nlohmann::json; 简化代码。json::parse_error 异常,建议用 try-catch 包裹。通过本文,你已经掌握了 nlohmann/json C++ JSON解析库 的基本使用方法,包括创建、解析、遍历和类型转换。无论你是开发网络应用、桌面软件还是嵌入式系统,这个库都能极大简化 JSON 数据的处理流程。
记住,熟练使用 C++处理JSON数据 是现代 C++ 工程师的重要技能。赶快在你的项目中试试 nlohmann/json 吧!
关键词回顾:nlohmann/json、C++ JSON解析库、C++处理JSON数据、JSON解析库
本文由主机测评网于2025-12-11发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025126373.html