C++解析Json的方法詳解【jsoncpp】
本文實(shí)例講述了C++解析Json的方法。分享給大家供大家參考,具體如下:
JSON(JavaScript Object Notation) 是一種輕量級(jí)的數(shù)據(jù)交換格式,和xml類似,本文主要對(duì)VS2008中使用Jsoncpp解析json的方法做一下記錄。
Jsoncpp是個(gè)跨平臺(tái)的開源庫(kù),下載地址:http://sourceforge.net/projects/jsoncpp/,我下載的是v0.5.0,壓縮包大約104K。
方法一:使用Jsoncpp生成的lib文件
解壓上面下載的Jsoncpp文件,在jsoncpp-src-0.5.0/makefiles/vs71目錄里找到j(luò)soncpp.sln,用VS2008版本編譯,默認(rèn)生成靜態(tài)鏈接庫(kù)。 在工程中引用,只需要包含include/json下的頭文件及生成的.lib文件即可。
如何包含lib文件:在.cpp文件中#pragma comment(lib."json_vc71_libmt.lib"),在工程屬性中Linker下Input中Additional Dependencies寫入lib文件名字(Release下為json_vc71_libmt.lib,Debug為json_vc71_libmtd.lib)
注意:Jsoncpp的lib工程編譯選項(xiàng)要和VS工程中的編譯選項(xiàng)保持一致。如lib文件工程編譯選項(xiàng)為MT(或MTd),VS工程中也要選擇MT(或MTd),否則會(huì)出現(xiàn)編譯錯(cuò)誤問題,debug和release下生成的lib文件名字不同,注意不要看錯(cuò)了,當(dāng)成一個(gè)文件來(lái)使用(我就犯了這個(gè)錯(cuò)誤)。
方法二:使用Jsoncpp包中的.cpp和.h文件
解壓上面下載的Jsoncpp文件,把jsoncpp-src-0.5.0文件拷貝到工程目錄下,將jsoncpp-src-0.5.0\jsoncpp-src-0.5.0\include\json和jsoncpp-src-0.5.0\jsoncpp-src-0.5.0\src\lib_json目錄里的文件包含到VS工程中,在VS工程的屬性C/C++下General中Additional Include Directories包含頭文件目錄.\jsoncpp-src-0.5.0\include。在使用的cpp文件中包含json頭文件即可,如:#include "json/json.h"。將json_reader.cpp、json_value.cpp和json_writer.cpp三個(gè)文件的Precompiled Header屬性設(shè)置為Not Using Precompiled Headers,否則編譯會(huì)出現(xiàn)錯(cuò)誤。
jsoncpp 使用詳解
jsoncpp 主要包含三種類型的 class:Value、Reader、Writer。jsoncpp 中所有對(duì)象、類名都在 namespace Json 中,包含 json.h 即可。
Json::Value 只能處理 ANSI 類型的字符串,如果 C++ 程序是用 Unicode 編碼的,最好加一個(gè) Adapt 類來(lái)適配。
下面是從網(wǎng)上找的代碼示例:
1. 從字符串解析json
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é)點(diǎn),upload_id = "UP000000"
int code = root["code"].asInt(); // 訪問節(jié)點(diǎn),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é)點(diǎn),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é)點(diǎn),Return the member named key if it exist, defaultValue otherwise.
int file_size = root["files"].size(); // 得到"files"的數(shù)組個(gè)數(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)建對(duì)象
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();
// 輸出無(wú)格式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();
}
備注:Json試用不當(dāng)會(huì)導(dǎo)致程序崩潰
Json::Value root; Json::Reader reader;
最好作為main函數(shù)的變量,不要作為全局變量,不要多次聲明(即,不要在循環(huán)或者在其他函數(shù)中聲明)。因?yàn)槠鋝tatic屬性,在第一次使用結(jié)束后會(huì)被析構(gòu),后來(lái)的使用就會(huì)訪問無(wú)效地址。
json_value.cpp中
Value::~Value() {
switch (type_) {
case nullValue:
case intValue:
case uintValue:
case realValue:
case booleanValue:
break;
case stringValue:
if (allocated_)
releaseStringValue(value_.string_);
break;
case arrayValue:
case objectValue:
delete value_.map_;//!!!!!!
break;
default:
JSON_ASSERT_UNREACHABLE;
}
正確的使用方式如下:
int getRebalancing(string str, Json::Value root, Json::Reader reader) ;
int main() {
Json::Value root;
Json::Reader reader;
while(1){
getRebalancing(string::str, root, reader);
//do something
}
return 0;
}
PS:這里再為大家推薦幾款比較實(shí)用的json在線工具供大家參考使用:
在線JSON代碼檢驗(yàn)、檢驗(yàn)、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在線格式化工具:
http://tools.jb51.net/code/jsonformat
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson
json代碼在線格式化/美化/壓縮/編輯/轉(zhuǎn)換工具:
http://tools.jb51.net/code/jsoncodeformat
C語(yǔ)言風(fēng)格/HTML/CSS/json代碼格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json
希望本文所述對(duì)大家C++程序設(shè)計(jì)有所幫助。
上一篇:C語(yǔ)言用棧實(shí)現(xiàn)十進(jìn)制轉(zhuǎn)換為二進(jìn)制的方法示例
欄 目:C語(yǔ)言
下一篇:c++中cin/cout與scanf/printf的區(qū)別比較
本文標(biāo)題:C++解析Json的方法詳解【jsoncpp】
本文地址:http://www.jygsgssxh.com/a1/Cyuyan/1498.html
您可能感興趣的文章
- 04-02c語(yǔ)言沒有round函數(shù) round c語(yǔ)言
- 01-10數(shù)據(jù)結(jié)構(gòu)課程設(shè)計(jì)- 解析最少換車次數(shù)的問題詳解
- 01-10深入理解C++中常見的關(guān)鍵字含義
- 01-10使用C++實(shí)現(xiàn)全排列算法的方法詳解
- 01-10深入解析最長(zhǎng)公共子串
- 01-10c++中inline的用法分析
- 01-10用C++實(shí)現(xiàn)DBSCAN聚類算法
- 01-10全排列算法的非遞歸實(shí)現(xiàn)與遞歸實(shí)現(xiàn)的方法(C++)
- 01-10C++大數(shù)模板(推薦)
- 01-10淺談C/C++中的static與extern關(guān)鍵字的使用詳解


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹的示例代碼(圣誕
- 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問題方法
- 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語(yǔ)言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 04-02c語(yǔ)言函數(shù)調(diào)用后清空內(nèi)存 c語(yǔ)言調(diào)用
- 04-02func函數(shù)+在C語(yǔ)言 func函數(shù)在c語(yǔ)言中
- 04-02c語(yǔ)言的正則匹配函數(shù) c語(yǔ)言正則表達(dá)
- 04-02c語(yǔ)言用函數(shù)寫分段 用c語(yǔ)言表示分段
- 04-02c語(yǔ)言中對(duì)數(shù)函數(shù)的表達(dá)式 c語(yǔ)言中對(duì)
- 04-02c語(yǔ)言編寫函數(shù)冒泡排序 c語(yǔ)言冒泡排
- 04-02c語(yǔ)言沒有round函數(shù) round c語(yǔ)言
- 04-02c語(yǔ)言分段函數(shù)怎么求 用c語(yǔ)言求分段
- 04-02C語(yǔ)言中怎么打出三角函數(shù) c語(yǔ)言中怎
- 04-02c語(yǔ)言調(diào)用函數(shù)求fibo C語(yǔ)言調(diào)用函數(shù)求
隨機(jī)閱讀
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10C#中split用法實(shí)例總結(jié)
- 01-10使用C語(yǔ)言求解撲克牌的順子及n個(gè)骰子
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
- 01-10delphi制作wav文件的方法
- 04-02jquery與jsp,用jquery
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?
- 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載


