json for modern c++(nlohmann json)使用小计

前言

一开始使用jsoncpp,可是jsoncpp已经不更新了,nlohmann还在更新,而且jsoncpp作过一次大的版本升级,致使api不兼容,之前使用过的工程代码不能很好的升级到新的版本,而且jsoncpp是多个文件支持,使用的时候我编译成了lib,nlohmann是一个头文件,更方便。c++

nlohmann使用c++11的新功能,更多的c++方法,使用起来更方便。而且nlohmann在调试的时候,能够看到数据结构,这个太有用了,而jsoncpp,只能经过内部的方法导出string。git

因为各类缘由把jsoncpp切换到nlohmann,在nlohmann使用时有一些须要注意的。不过大部分注意事项做者已经写到github上了 https://github.com/nlohmann/jsongithub

因为做者是基于json标准的,我fork了一个分支,增长了一些易用性的不是在json标准中的功能
json

https://github.com/studywithallofyou/jsonapi

1.

nlohmann支持隐式转换,可是不要使用,由于行为不肯定数组

看下面的例子及输出结果数据结构

long long lnum = 327221437; nlohmann::json a; a["num1"] = 327220625; nlohmann::json b; b["num2"] = 900000; if (lnum - a["num1"] > b["num2"]) { cout << lnum << endl; cout << a["num1"] << endl; cout << b["num2"] << endl; cout << lnum - a["num1"] << endl; cout << lnum - a["num1"].get<long long>() << endl; }
/*
327221437 327220625 900000 327221292 812
*/

lnum - a["num1"] > b["num2"]并不成立,可是进来了,若是写成lnum - a["num1"].get<long long>() > b["num2"].get<long long>()就没问题spa

2.

在调用json::parse(iter.begin(), iter.end())的时候须要注意,做者也说了,是[iter.begin(), iter.end()),左闭右开的,因此若是是一个数组保存了json字符串,那么就是a, a+len,而不是a, a+len-1调试

3.

nlohmann::json::parse若是是非法的json会直接丢一个异常,能够经过nlohmann::json::accept判断是否合法c++11

相关文章
相关标签/搜索