怎么在C++中使用jsoncpp對(duì)json進(jìn)行解析?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
創(chuàng)新互聯(lián)主要從事網(wǎng)站制作、成都網(wǎng)站設(shè)計(jì)、網(wǎng)頁(yè)設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)豐臺(tái),10年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來(lái)電咨詢建站服務(wù):18982081108
jsoncpp中主要的類:
Json::Value:可以表示所有支持的類型,如:int , double ,string , object, array等。其包含節(jié)點(diǎn)的類型判斷(isNull,isBool,isInt,isArray,isMember,isValidIndex等),類型獲取(type),類型轉(zhuǎn)換(asInt,asString等),節(jié)點(diǎn)獲取(get,[]),節(jié)點(diǎn)比較(重載<,<=,>,>=,==,!=),節(jié)點(diǎn)操作(compare,swap,removeMember,removeindex,append等)等函數(shù)。
Json::Reader:將文件流或字符串創(chuàng)解析到Json::Value中,主要使用parse函數(shù)。Json::Reader的構(gòu)造函數(shù)還允許用戶使用特性Features來(lái)自定義Json的嚴(yán)格等級(jí)。
Json::Writer:與JsonReader相反,將Json::Value轉(zhuǎn)換成字符串流等,Writer類是一個(gè)純虛類,并不能直接使用。在此我們使用 Json::Writer 的子類:Json::FastWriter(將數(shù)據(jù)寫入一行,沒有格式),Json::StyledWriter(按json格式化輸出,易于閱讀)。
Json::Reader可以通過(guò)對(duì)Json源目標(biāo)進(jìn)行解析,得到一個(gè)解析好了的Json::Value,通常字符串或者文件輸入流可以作為源目標(biāo)。
json示例:
[ { "name": "json", "lines": [ { "line": "1" }, { "line": "2" }, { "cpp": "jsoncpp" }, { "java": "jsoninjava" }, { "php": "support" } ] }, { "name": "c++", "lines": [ { "line": "3" }, { "line": "4" }, { "cpp": "jsoncpp" }, { "java": "jsoninjava" }, { "php": "nosupport" } ] } ]
C++代碼:
#include <iostream> #include <fstream> #include <string> #include "../src/json/json.h" using namespace std; using namespace Json; void main() { fstream ofile("json.json"); string strjson; if (!ofile.is_open()) { return; } string strline; while (getline(ofile, strline)) { strjson += strline; } ofile.close(); Json::Reader reader; // 讀取器 Json::Value root; // Value的值值可以是任一對(duì)象 if (reader.parse(strjson, root)) { int size = root.size(); // 根結(jié)點(diǎn)個(gè)數(shù) for (int j = 0; j < size; j++) { cout << root[j]["name"].asString() << endl; const Json::Value arrayObj = root[j]["lines"]; for (int i = 0; i < arrayObj.size(); i++) { if (arrayObj[i].isMember("line")) { cout << arrayObj[i]["line"].asString() << endl; } if (arrayObj[i].isMember("cpp")) { cout << arrayObj[i]["cpp"].asString() << endl; } if (arrayObj[i].isMember("java")) { cout << arrayObj[i]["java"].asString() << endl; } int m = 0; } } } }
看完上述內(nèi)容,你們掌握怎么在C++中使用jsoncpp對(duì)json進(jìn)行解析的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
本文標(biāo)題:怎么在C++中使用jsoncpp對(duì)json進(jìn)行解析
標(biāo)題網(wǎng)址:http://bm7419.com/article26/pphccg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站收錄、響應(yīng)式網(wǎng)站、移動(dòng)網(wǎng)站建設(shè)、手機(jī)網(wǎng)站建設(shè)、網(wǎng)站排名、App開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)