1、相關概念總結
(1)解析json的方法
Json::Value json; //表示一個json格式的對象
Json::Reader reader; //json解析
reader.parse(json_buf/*json格式的字元串*/,json,false); //解析出json放到json中
jsoncpp庫中的Reader類用來将字串或者流載入解析器。後期可以用Reader裡面的解析方法把Json字串解碼為C++認識的資料。可以用 Json::Reader來聲明一個Reader執行個體。Reader中最常用的就是一個parse方法,該方法用來将載入的json字串解析為C++格式的資料。
(2) 數組通路
Json::Value //格式如下
[["key1":value1],["key2":value2]]
Json::Value::const_iterator iter; //疊代器
for(iter = input.begin(); iter != input.end(); iter++)
Json::Value::Members member=(*iter).getMemberNames();
*(member.begin()); // 輸出 key1,key2
(*iter)[*(member.begin())]; //輸出 value1,value2
Value類是庫中的核心類,用于存儲各樣格式的資料,可以包括int,double,short,char *,string,bool,object,array等幾乎所有格式的資料。該庫的編碼和解碼的核心功能都是用Value類實作的。就用以上的 Reader的parse方法來說,需要傳入一個Value類别的引用值,就是用來存儲Json資料的根值,并且可以用這個根值來存取其他的所有值。
(3) 對象通路
直接用 value["key"]即可
(4) 輸出json格式串
調用 Json::FastWriter的writer
writer是該庫的一個虛類,沒有真正的實作encode的功能。需要重載裡頭的方法來實作真正的encode功能。FastWriter是該庫中真正實作encode功能的類,用來實作将Value編碼稱為Json串。Json::StyledWriter 是格式化後的json。
不支援utf-8格式的輸出,需要自己調用writer之後,用iconv轉化成utf-8字元串
2、示例代碼
1)示例代碼1

View Code

結果顯示
可以看到,直接用wirter輸出的json為非格式化的資料,而通過root.toStyledString()後,代碼就是格式化的。
2)示例3,來源于官網


參考
【1】 講解說明
<a href="http://hi.baidu.com/%B4%AB%CB%B5%D6%D0%B5%C4%C8%CC%D5%DF%C3%A8/blog/item/a6eb970c98a644d67acbe15a.html">http://hi.baidu.com/%B4%AB%CB%B5%D6%D0%B5%C4%C8%CC%D5%DF%C3%A8/blog/item/a6eb970c98a644d67acbe15a.html</a>
【2】 示例,該作者博文不錯,涵蓋了各個方面
<a href="http://hi.baidu.com/s_jqzhang/blog/item/a3c5df1f9408246ff624e4f5.html/cmtid/02e72e4fcb488039aec3ab28">http://hi.baidu.com/s_jqzhang/blog/item/a3c5df1f9408246ff624e4f5.html/cmtid/02e72e4fcb488039aec3ab28</a>
【3】 boost庫支援json比較好
<a href="http://freedomhui.com/?p=6">http://freedomhui.com/?p=6</a>
【3】 對json的類型作了簡單的小結,為json-c進行了介紹
<a href="http://developer.51cto.com/art/201001/176060.htm">http://developer.51cto.com/art/201001/176060.htm</a>
【4】 官網
<a href="http://jsoncpp.sourceforge.net/index.html">http://jsoncpp.sourceforge.net/index.html</a>
相關的類介紹及使用
<a href="http://jsoncpp.sourceforge.net/annotated.html">http://jsoncpp.sourceforge.net/annotated.html</a>
【5】 其他例子