JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式,和xml類似,本文主要對VS2008中使用Jsoncpp解析json的方法做一下記錄。
解壓上面下載的Jsoncpp文件,在jsoncpp-src-0.5.0/makefiles/vs71目錄里找到j(luò)soncpp.sln,用VS2008版本編譯,默認(rèn)生成靜態(tài)鏈接庫。 在工程中引用,只需要包含include/json下的頭文件及生成的.lib文件即可。
jsoncpp 使用詳解 jsoncpp 主要包含三種類型的 class:Value、Reader、Writer。jsoncpp 中所有對象、類名都在 namespace Json 中,包含 json.h 即可。 Json::Value 只能處理 ANSI 類型的字符串,如果 C++ 程序是用 Unicode 編碼的,最好加一個 Adapt 類來適配。
const char* str = '{\'uploadid\': \'UP000000\',\'code\': 100,\'msg\': \'\',\'files\': \'\'}'; Json::Reader reader; Json::Value root; if (reader.parse(str, root)) // reader將Json字符串解析到root,root將包含Json里所有子元素 { std::string upload_id = root['uploadid'].asString(); // 訪問節(jié)點,upload_id = 'UP000000' int code = root['code'].asInt(); // 訪問節(jié)點,code = 100 }
2. 從文件解析json int ReadJsonFromFile(const char* filename) { Json::Reader reader;// 解析json用Json::Reader Json::Value root; // Json::Value是一種很重要的類型,可以代表任意類型。如int, string, object, array std::ifstream is; is.open (filename, std::ios::binary ); if (reader.parse(is, root, FALSE)) { std::string code; if (!root['files'].isNull()) // 訪問節(jié)點,Access an object value by name, create a null member if it does not exist. code = root['uploadid'].asString(); code = root.get('uploadid', 'null').asString();// 訪問節(jié)點,Return the member named key if it exist, defaultValue otherwise. int file_size = root['files'].size(); // 得到'files'的數(shù)組個數(shù) for(int i = 0; i < file_size;="" ++i)="">// 遍歷數(shù)組 { Json::Value val_image = root['files'][i]['images']; int image_size = val_image.size(); for(int j = 0; j < image_size;="">j) { std::string type = val_image[j]['type'].asString(); std::string url = val_image[j]['url'].asString(); printf('type : %s, url : %s \n', type.c_str(), url.c_str()); } } } is.close(); return 0; }
3. 向文件中插入json
void WriteJsonData(const char* filename){ Json::Reader reader; Json::Value root; // Json::Value是一種很重要的類型,可以代表任意類型。如int, string, object, array std::ifstream is; is.open (filename, std::ios::binary ); if (reader.parse(is, root)) { Json::Value arrayObj; // 構(gòu)建對象 Json::Value new_item, new_item1; new_item['date'] = '2011-11-11'; new_item1['time'] = '11:11:11'; arrayObj.append(new_item); // 插入數(shù)組成員 arrayObj.append(new_item1); // 插入數(shù)組成員 int file_size = root['files'].size(); for(int i = 0; i < file_size;="">i) root['files'][i]['exifs'] = arrayObj; // 插入原json中 std::string out = root.toStyledString(); // 輸出無格式j(luò)son字符串 Json::FastWriter writer; std::string strWrite = writer.write(root); std::ofstream ofs; ofs.open('test_write.json'); ofs strWrite; ofs.close(); } is.close(); } 4.序列化json字符串 先構(gòu)建一個Json對象,此Json對象中含有數(shù)組,然后把Json對象序列化成字符串,代碼如下: Json::Value root; Json::Value arrayObj; Json::Value item; for (int i=0; i10; i++) { item['key'] = i; arrayObj.append(item); } root['key1'] = “value1″; root['key2'] = “value2″; root['array'] = arrayObj; root.toStyledString(); std::string out = root.toStyledString(); std::cout <>out std::endl;
5.反序列化json 比如一個Json對象的字符串序列如下,其中”array”:[...]表示Json對象中的數(shù)組:{“key1″:”value1″,”array”:[{'key2':'value2'},{'key2':'value3'},{'key2':'value4'}]},那怎么分別取到key1和key2的值呢,代碼如下所示: std::string strValue = “{\”key1\”:\”value1\”,\”array\”:[{\'key2\':\'value2\'},{\'key2\':\'value3\'},{\'key2\':\'value4\'}]}”; Json::Reader reader; Json::Value value; if (reader.parse(strValue, value)) { std::string out = value['key1'].asString(); std::cout <>out std::endl; const Json::Value arrayObj = value['array']; for (int i=0; i 6.刪除json子對象 std::string strContent = '{\'key\':\'1\',\'name\':\'test\'}'; Json::Reader reader; Json::Value value; if (reader.parse(strContent, value)) { Json::Value root=value; root.removeMember('key'); printf('%s \n',root.toStyledString().c_str()); } 7. 利用jsoncpp將json字符串轉(zhuǎn)換為Vector 在API測試過程中經(jīng)常會遇到傳入?yún)?shù)為復(fù)雜類型,一般情況下在python下,習(xí)慣用字典來表示復(fù)雜類型。但是c++對字符串的處理是比較弱智的,一般c++里邊會用vector來存儲復(fù)雜類型,那么就存在轉(zhuǎn)換的問題,下面小段代碼記錄了將字符串轉(zhuǎn)換為Vector的過程 待轉(zhuǎn)換的字符串如下: const char * jsongroupinfo='[{/'groupId/' :946838524,/'groupname/' :/'bababa/', /'mask/':1,/'parentid/':946755072}]'; Json::Reader reader;Json::Value json_object;if (!reader.parse(jsongroupinfo, json_object)) return 'parse jsonstr error';SUserChggroup sucg;VECTOR< suserchggroup=""> m_groupInfo;for(int i = 0; i < json_object.size();="" i="">){ Json::Value ¤t = json_object[i]; sucg.m_groupId = current['groupId'].asInt(); sucg.m_groupName = current['groupname'].asString(); sucg.m_mask = current['mask'].asInt(); sucg.m_parentId = current['parentid'].asInt(); m_groupInfo.push_back(sucg);}
簡而言之,就是把它變成解析成一個個對象,再將對象存儲到vector中。
ps:在使用vs2005調(diào)用vs2010編譯的dll時候,出現(xiàn)string的內(nèi)存錯誤,在不同版本的string的不能相互傳遞,用const char *比較好,相關(guān)代碼修改: std::string strRtn = '{'success':true,'user':{'id':6,'username':'wq','type':'admin','membership':{'type':'paid','expiredAt':'2019-07-28T16:00:00.000Z'}},'token':'8de57200-3235-11e8-83f1-9739d2f0386f'}'; std::string strToken; Json::Reader reader; //解析json用Json::Reader Json::Value value; //可以代表任意類型 if (reader.parse(strRtn.c_str(),strRtn.c_str()+strRtn.size(), value)) { if (value['success'].asBool()) { strToken = value['token'].asCString(); } } |
|
來自: 西北望msm66g9f > 《編程》