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