生活随笔
收集整理的這篇文章主要介紹了
推荐一款cpp解析json工具--rapidjson
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
項目地址:http://code.google.com/p/rapidjson/
上面有很詳細的介紹:http://code.google.com/p/rapidjson/wiki/UserGuide
作者介紹說:"?Rapidjsonis an attempt to create?the fastest?JSON parser and generator.?"
這是一個試圖創(chuàng)造出一個最快的json解析和生成項目 呵呵。
?
嘛也不說 通過一個例子來看看這個工具的好用之處。
[html]?view plaincopy print?
#include?"rapidjson/document.h"?//?rapidjson's?DOM-style?API?? #include?"rapidjson/prettywriter.h"?//?for?stringify?JSON?? #include?"rapidjson/filestream.h"???????//?wrapper?of?C?stream?for?prettywriter?as?output?? #include?<cstdio>?? ?? using?namespace?rapidjson;?? ?? int?main()?? {??????? ????char?json[100]?=?"{?\"hello\"?:?\"world\"?}";??? ????rapidjson::Document?d;??????? ????d.Parse<0>(json);???????? ????printf("%s\n",?d["hello"].GetString());?????? ????printf("%s\n",?json);?????? ????getchar();?? ????return?0;??? }??
?
輸出:
下面說說這個開源程序的幾個特點:
優(yōu)點:
1.依賴庫很少,
2.輕量級
3.對于Dom模型層級關(guān)系表述的很清楚
?
缺點:
1。只支持標準的json格式,一些非標準的json格式不支持
2。缺少一些比較通用的接口,再解析的時候需要自己再封裝一層,否則代碼量將會很大。
?
舉個例子:
Json數(shù)據(jù)
{ "hello" : "world","t" : true , "f" : false, "n": null,"i":123, "pi": 3.1416, "a":[1, 2, 3, 4] }
?
為了獲取a中第三個元素的值就得進行如下的操作:
[html]?view plaincopy print?
int?main()?? {??????? ????//char?json[100]?=?"{?\"hello\"?:?\"world\"?}";??? ?????? ????const?char?json[]?=?"?{?\"hello\"?:?\"world\",?\"t\"?:?true?,?\"f\"?:?false,?\"n\":?null,?\"i\":123,?\"pi\":?3.1416,?\"a\":[1,?2,?3,?4]?}?";?? ?? ????rapidjson::Document?d;??????? ????d.Parse<0>(json);???????? ????if?(d.HasParseError())?? ????{?? ????????printf("GetParseError?%s\n",d.GetParseError());?? ????}?? ?? ????if?(d.HasMember("a"))//這個時候要保證d濕IsObject類型?最好是?if(d.Isobject()?&&?d.HasMember("a"))?? ????{?? ????????const?Value?&a=d["a"];?? ????????if?(a.IsArray()?&&?a.Size()?>?3)?? ????????{?? ????????????const?Value?&a3=a[2];?? ????????????string?stra3;?? ????????????ValueToString(a3,?stra3);?? ????????????if?(a3.IsInt())?? ????????????{?? ????????????????????printf("GetInt?[%d]?\n",a3.GetInt());?;?? ????????????}?? ????????}?? ????}?? ?????? ????getchar();?? ????return?0;??? }??
可以看到為了獲取一個二級的數(shù)據(jù)需要進行一層層的解析和類型判斷,否則程序就會崩潰。
這里注意的一點HasMember 也必須是Isobject才能調(diào)用否則程序也會調(diào)用失敗。
建議可以封裝出以下幾個接口:
int?ValueToString(const Value &node ,string &strRet);
int?ValueToLong(const Value &node ,long &lRet);
int GetChildNode(const Value &Pnode,vector<string> &listCfg, Value &ChildNode ) ;
int GetChildNode(const Value &Pnode,const intiArrSize, char[][32] &szArrCfg, Value &ChildNode ) ;
之類的接口。
?源碼下載
不對之處敬請諒解~~ 歡迎交流~~~
總結(jié)
以上是生活随笔為你收集整理的推荐一款cpp解析json工具--rapidjson的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。