Json解析數組執行個體
1. JsonCPP簡介
jsoncpp是c++解析JSON串常用的解析庫之一。其常用的類有:
a) Json::Value 可以表示裡所有的類型,比如int,string,object,array等,其支援的類型可以參考Json:ValueType中的值。
b) Json::Reader 將json檔案流或字串解析到Json::Value,主要函數有Parse。
c) Json::Writer 與Json::Reader相反,將Json::Value轉化成字串流,注意它的兩個子類:Json::FastWriter和Json::StyleWriter,分別輸出不帶格式的json和帶格式的json。
d) Json::Value::Members 主要用於以STL風格解析JSON數組。看過原始碼的人已知道,Members其實是typedefvector而已。
2. JSONCPP解析樣本
a) 解析JSON串格式
{
"JsonID": "BD6D7FDA-54D2-468b-A3DE-9D5FBDB78207",
"Send": {
"ID": "B8E09E97-F379-4bb0-814A-389FD3F66631",
"Items": [
{
"Count": 2,
"Code": "0101",
"X": 1,
"Y": 2
},
{
"Count": 2,
"Code": "0101",
"X": 1,
"Y": 2
}
]
}
}
b) 產生的JSON串
{
"Ack": [
{
"ActualCount": 2,
"Code": "0101"
},
{
"ActualCount": 2,
"Code": "0101"
}
],
"JsonID": "BD6D7FDA-54D2-468b-A3DE-9D5FBDB78207"
}
c) 解析、產生JSON代碼
需要引入的.h檔案
[html] view plaincopy
- #pragma once
- #pragma comment(lib, "json_vc71_libmtd.lib")
- #include "json/json.h"
實現
[cpp] view plaincopy
- void CJSONTestDlg::OnBnClickedButton1()
- {
- CEdit* pEdit =(CEdit*)GetDlgItem(IDC_EDIT1);
- CString str;
- pEdit->GetWindowText(str); //str即為a)中定義的JSON串
- pEdit->FmtLines(true);
- Json::Reader reader;
- Json::Value root;
- if (reader.parse(WC2UT(str.GetBuffer(0)), root)) // reader將Json字串解析到root,root將包含Json裡所有子項目
- {
- std::string JsonID = root["JsonID"].asString();
- Json::Value rtnRoot;
- rtnRoot["JsonID"]=JsonID;
- Json::Value ack;
- Json::Value send = root["Send"];
- if(!send["Items"].isNull()){
- Json::Value Items = send["Items"];
- int sendSize = Items.size();
- for(int i=0;i std::string Code = Items[i]["Code"].asString();
- int x = Items[i]["X"].asInt();
- int y = Items[i]["Y"].asInt();
- int count = Items[i]["Count"].asInt();
- //更具讀到的JSON串中的值產生所需內容
- Json::Value newAckItem;
- newAckItem["Code"]=Code;
- newAckItem["ActualCount"]=count;
- ack.append(newAckItem);
- }
- }
- rtnRoot["Ack"]=ack;
- std::string rtnOut = rtnRoot.toStyledString();//產生帶格式的JSON串
- #ifdef UNICODE
- std::wstring stemp = s2ws(rtnOut);
- LPCWSTR result = stemp.c_str();
- #else
- LPCWSTR result = rtnOut.c_str();
- #endif
- MessageBox(result,_T("根據JSON串,產生的對應JSON串資訊"));
- CEdit* pEdit =(CEdit*)GetDlgItem(IDC_EDIT2);
- pEdit->SetWindowText(result);
- }else{
- CEdit* pRtnEdit =(CEdit*)GetDlgItem(IDC_EDIT2);
- pRtnEdit->SetWindowText(_T("JSON格式錯誤"));
- }
- }
將JSONCPP以靜態庫方式匯入,需要注意項目中的代碼產生中的運行庫,和JSONCPP的靜態庫項目的代碼產生的運行庫要一致,否則將報如下錯誤
afxver_.h(81): fatal error C1189: #error : Please use the /MD switch for _AFXDLL builds
項目中的Runtime Library需設定的一樣