C++ 解析Json(jsoncpp)使用方法
JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式,和xml類似,本文主要對VS2008中使用Jsoncpp解析json的方法做一下記錄。Jsoncpp是個跨平臺的開源庫,下載地址:http://sourceforge.net/projects/jsoncpp/,我下載的是v0.5.0,壓縮包大約104K。
方法一:使用Jsoncpp生成的lib檔案
解壓上面下載的Jsoncpp檔案,在jsoncpp-src-0.5.0/makefiles/vs71目錄裡找到jsoncpp.sln,用VS2008版本編譯,預設生成靜態連結庫。 在工程中引用,只需要包含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工程編譯選項要和VS工程中的編譯選項保持一致。如lib檔案工程編譯選項為MT(或MTd),VS工程中也要選擇MT(或MTd),否則會出現編譯錯誤問題,debug和release下生成的lib檔名字不同,注意不要看錯了,當成一個檔案來使用(我就犯了這個錯誤)。
方法二:使用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"。將
jsoncpp 使用詳解
jsoncpp 主要包含三種類型的 class:Value、Reader、Writer。jsoncpp 中所有物件、類名都在 namespace Json 中,包含 json.h 即可。
Json::Value 只能處理 ANSI 型別的字串,如果 C++ 程式是用 Unicode 編碼的,最好加一個 Adapt 類來適配。
下面是從網上找的程式碼示例:
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(); // 訪問節點,upload_id = "UP000000"
int code = root["code"].asInt(); // 訪問節點,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()) // 訪問節點,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();// 訪問節點,Return the member named key if it exist, defaultValue otherwise.
int file_size = root["files"].size(); // 得到"files"的陣列個數
for(int i = 0; i < file_size; ++i) // 遍歷陣列
{
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; // 構建物件
Json::Value new_item, new_item1;
new_item["date"] = "2011-11-11";
new_item1["time"] = "11:11:11";
arrayObj.append(new_item); // 插入陣列成員
arrayObj.append(new_item1); // 插入陣列成員
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();
// 輸出無格式json字串
Json::FastWriter writer;
std::string strWrite = writer.write(root);
std::ofstream ofs;
ofs.open("test_write.json");
ofs << strWrite;
ofs.close();
}
is.close();
}
陣列迴圈解析,使用方法如下:
if(!root["list"].isNull())
{
for (int nIndex = 0; nIndex < root["list"].size(); nIndex++)
{
CString sTitleTemp = root["list"][nIndex]["title"].asCString();
}
}
4.序列化json字串
先構建一個Json物件,此Json物件中含有陣列,然後把Json物件序列化成字串,程式碼如下:
Json::Value root;
Json::Value arrayObj;
Json::Value item;
for (int i=0; i<10; 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物件中的陣列:
{“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<arrayObj.size(); i++)
{
out = arrayObj[i]["key2"].asString();
std::cout << out;
if (i != arrayObj.size() – 1 )
std::cout << std::endl;
}
}
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字串轉換為Vector
在API測試過程中經常會遇到傳入引數為複雜型別,一般情況下在python下,習慣用字典來表示複雜型別。但是c++對字串的處理是比較弱智的,一般c++裡邊會用vector來儲存複雜型別,那麼就存在轉換的問題,下面小段程式碼記錄了將字串轉換為Vector的過程
待轉換的字串如下:
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);
}