JSONforModernC++是一个由德国大牛nlohmann编写的在C++下使用的JSON库。
具有以下特点
直观的语法
整个代码由一个头文件组成json.hpp,没有子项目,没有依赖关系,没有复杂的构建系统,使用起来非常方便
使用C++11标准编写
使用json像使用STL容器一样
STL和json容器之间可以相互转换
严谨的测试:所有类都经过严格的单元测试,覆盖了100%的代码,包括所有特殊的行为。此外,还检查了Valgrind是否有内存泄漏。为了保持高质量,该项目遵循核心基础设施倡议(CII)的最佳实践
示例代码
假设要创建如下的JSON对象
{ "pi": 3.141, "happy": true, "name": "Niels", "nothing": null, "answer": { "everything": 42 }, "list": [1, 0, 2], "object": { "currency": "USD", "value": 42.99 }}使用这个JSON库,可以这样写
// create an empty structure (null)json j;// add a number that is stored as double (note the implicit conversion of j to an object)j["pi"] = 3.141;// add a Boolean that is stored as boolj["happy"] = true;// add a string that is stored as std::stringj["name"] = "Niels";// add another null object by passing nullptrj["nothing"] = nullptr;// add an object inside the objectj["answer"]["everything"] = 42;// add an array that is stored as std::vector (using an initializer list)j["list"] = { 1, 0, 2 };// add another object (using an initializer list of pairs)j["object"] = { {"currency", "USD"}, {"value", 42.99} };// instead, you could also write (which looks very similar to the JSON above)json j2 = { {"pi", 3.141}, {"happy", true}, {"name", "Niels"}, {"nothing", nullptr}, {"answer", { {"everything", 42} }}, {"list", {1, 0, 2}}, {"object", { {"currency", "USD"}, {"value", 42.99} }}};请注意,在所有上述情况下,不需要“告诉”编译器要使用哪个JSON值。如果想要明确或表达一些边缘的情况,可以使用 json::array 和 json::object
// a way to express the empty array []json empty_array_explicit = json::array();// ways to express the empty object {}json empty_object_implicit = json({});json empty_object_explicit = json::object();// a way to express an _array_ of key/value pairs [["currency", "USD"], ["value", 42.99]]json array_not_object = json::array({ {"currency", "USD"}, {"value", 42.99} });
评论