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