作为一个被 Spring Boot 自动配置折磨多年的 Java 老兵,第一次看到 nlohmann/json 时,我差点以为自己穿越到了 Python 世界——这真的是 C++ 能写出来的代码?
单头文件的魔法:include 即用
nlohmann/json 最震撼的地方在于它的交付方式:整个库就一个头文件 json.hpp。不需要编译、不需要链接、不用折腾 CMakeLists.txt,只要:
#include <nlohmann/json.hpp> // for convenience using json = nlohmann::json;
两行代码,搞定一切。这种"零配置"体验在 C++ 生态中堪称奢侈。对比传统 C++ 库动辄需要处理依赖、编译选项、链接错误的痛苦,nlohmann/json 简直是开发者的救星。
如果你坚持要用包管理器,它也支持 CMake 的 find_package:
find_package(nlohmann_json 3.12.0 REQUIRED)
target_link_libraries(foo PRIVATE nlohmann_json::nlohmann_json)
但说实话,直接拷贝头文件可能是最简单的方式。
像写 JSON 字面量一样写 C++ 代码
这个库的核心设计理念是:让 JSON 操作变得像原生类型一样自然。看看这个初始化代码:
// create an empty structure (null)
json j;
// add a number stored as double (note the implicit conversion of j to an object)
j["pi"] = 3.141;
// add a Boolean stored as bool
j["happy"] = true;
// add a string stored as std::string
j["name"] = "Niels";
// add another null object by passing nullptr
j["nothing"] = nullptr;
// add an object inside the object
j["answer"]["everything"] = 42;
// add an array stored as std::vector (using an initializer list)
j["list"] = { 1, 0, 2 };
// add another object (using an initializer list of pairs)
j[] = { {, }, {, } };


