JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式,和xml類似,本文主要對VS2008中使用Jsoncpp解析json的方法做一下記錄攻走。
Jsoncpp是個跨平臺的開源庫,下載地址:http://sourceforge.net/projects/jsoncpp/。
方法一:使用Jsoncpp生成的lib文件
解壓上面下載的Jsoncpp文件,在jsoncpp-src-0.5.0/makefiles/vs71目錄里找到jsoncpp.sln君仆,用VS2008版本編譯,默認生成靜態(tài)鏈接庫牲距。 在工程中引用返咱,只需要包含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)萤晴,否則會出現(xiàn)編譯錯誤問題吐句,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"。將json_reader.cpp紧武、json_value.cpp和json_writer.cpp三個文件的Precompiled Header屬性設置為Not Using Precompiled Headers剃氧,否則編譯會出現(xiàn)錯誤。
jsoncpp 使用詳解
jsoncpp 主要包含三種類型的 class:Value阻星、Reader朋鞍、Writer。jsoncpp 中所有對象妥箕、類名都在 namespace Json 中滥酥,包含 json.h 即可。
Json::Value 只能處理 ANSI 類型的字符串畦幢,如果 C++ 程序是用 Unicode 編碼的坎吻,最好加一個 Adapt 類來適配。
下面是從網(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é)點瘦真,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; // 構建對象
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();
// 輸出無格式json字符串
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字符串
先構建一個Json對象膀哲,此Json對象中含有數(shù)組往产,然后把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對象中的數(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<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());
}
- 利用jsoncpp將json字符串轉換為Vector
在API測試過程中經(jīng)常會遇到傳入?yún)?shù)為復雜類型,一般情況下在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);
}
簡而言之酱酬,就是把它變成解析成一個個對象,再將對象存儲到vector中云矫。
ps:在使用vs2005調(diào)用vs2010編譯的dll時候膳沽,出現(xiàn)string的內(nèi)存錯誤,在不同版本的string的不能相互傳遞,用const char *比較好让禀,相關代碼修改:
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();
}
}