前言
一開始使用jsoncpp,但是jsoncpp已經不更新了,nlohmann還在更新,並且jsoncpp做過一次大的版本升級,導致api不兼容,以前使用過的工程代碼不能很好的升級到新的版本,並且jsoncpp是多個文件支持,使用的時候我編譯成了lib,nlohmann是一個頭文件,更方便。
nlohmann使用c++11的新功能,更多的c++方法,使用起來更方便。並且nlohmann在調試的時候,可以看到數據結構,這個太有用了,而jsoncpp,只能通過內部的方法導出string。
由於各種原因把jsoncpp切換到nlohmann,在nlohmann使用時有一些需要注意的。不過大部分注意事項作者已經寫到github上了 https://github.com/nlohmann/json
由於作者是基於json標准的,我fork了一個分支,增加了一些易用性的不是在json標准中的功能
https://github.com/studywithallofyou/json
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>()就沒問題
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判斷是否合法