一. 使用jsoncpp解析json
Jsoncpp是個跨平台的開源庫,首先從http://jsoncpp.sourceforge.net/上下載jsoncpp庫源碼,我下載的是v0.5.0,壓縮包大約107K,解壓,在jsoncpp-src-0.5.0/makefiles/vs71目錄里找到jsoncpp.sln,用VS2003及以上版本編譯,默認生成靜態鏈接庫。 在工程中引用,只需要include/json及.lib文件即可。
使用JsonCpp前先來熟悉幾個主要的類:
Json::Value 可以表示里所有的類型,比如int,string,object,array等,具體應用將會在后邊示例中介紹。
Json::Reader 將json文件流或字符串解析到Json::Value, 主要函數有Parse。
Json::Writer 與Json::Reader相反,將Json::Value轉化成字符串流,注意它的兩個子類:Json::FastWriter和Json::StyleWriter,分別輸出不帶格式的json和帶格式的json。
1. 從字符串解析json
- int ParseJsonFromString()
- {
- 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
- }
- return 0;
- }
int ParseJsonFromString()
{
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
}
return 0;
}
2. 從文件解析json
json文件內容:
- {
- "uploadid": "UP000000",
- "code": "0",
- "msg": "",
- "files":
- [
- {
- "code": "0",
- "msg": "",
- "filename": "1D_16-35_1.jpg",
- "filesize": "196690",
- "width": "1024",
- "height": "682",
- "images":
- [
- {
- "url": "fmn061/20111118",
- "type": "large",
- "width": "720",
- "height": "479"
- },
- {
- "url": "fmn061/20111118",
- "type": "main",
- "width": "200",
- "height": "133"
- }
- ]
- }
- ]
- }
{
"uploadid": "UP000000",
"code": "0",
"msg": "",
"files":
[
{
"code": "0",
"msg": "",
"filename": "1D_16-35_1.jpg",
"filesize": "196690",
"width": "1024",
"height": "682",
"images":
[
{
"url": "fmn061/20111118",
"type": "large",
"width": "720",
"height": "479"
},
{
"url": "fmn061/20111118",
"type": "main",
"width": "200",
"height": "133"
}
]
}
]
}
解析代碼:
- int ParseJsonFromFile(const char* filename)
- {
- // 解析json用Json::Reader
- Json::Reader reader;
- // Json::Value是一種很重要的類型,可以代表任意類型。如int, string, object, array...
- Json::Value root;
- std::ifstream is;
- is.open (filename, std::ios::binary );
- if (reader.parse(is, root))
- {
- 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();
- // 訪問節點,Return the member named key if it exist, defaultValue otherwise.
- code = root.get("uploadid", "null").asString();
- // 得到"files"的數組個數
- int file_size = root["files"].size();
- // 遍歷數組
- 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();
- }
- }
- }
- is.close();
- return 0;
- }
int ParseJsonFromFile(const char* filename)
{
// 解析json用Json::Reader
Json::Reader reader;
// Json::Value是一種很重要的類型,可以代表任意類型。如int, string, object, array...
Json::Value root;
std::ifstream is;
is.open (filename, std::ios::binary );
if (reader.parse(is, root))
{
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();
// 訪問節點,Return the member named key if it exist, defaultValue otherwise.
code = root.get("uploadid", "null").asString();
// 得到"files"的數組個數
int file_size = root["files"].size();
// 遍歷數組
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();
}
}
}
is.close();
return 0;
}
3. 在json結構中插入json
- Json::Value arrayObj; // 構建對象
- Json::Value new_item, new_item1;
- new_item["date"] = "2011-12-28";
- new_item1["time"] = "22:30:36";
- 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中
Json::Value arrayObj; // 構建對象
Json::Value new_item, new_item1;
new_item["date"] = "2011-12-28";
new_item1["time"] = "22:30:36";
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中
4. 輸出json
- // 轉換為字符串(帶格式)
- std::string out = root.toStyledString();
- // 輸出無格式json字符串
- Json::FastWriter writer;
- std::string out2 = writer.write(root);
// 轉換為字符串(帶格式) std::string out = root.toStyledString(); // 輸出無格式json字符串 Json::FastWriter writer; std::string out2 = writer.write(root);
jsoncpp的一些使用方法介紹:
1、初始化
Json::Value root;
Json::Reader reader;
reader.parse(“{“name”:”sunny”}”, root);
Reader可以用來初始化一個人json從字符串。
2、讀取json文件初始化
這是我寫的一個方法:
|
3、解析json
首先生成一個json
Json::Value myjson = getJsonFromFile(“test.json”); //利用上面的函數生成一個json。
int num = myJson["num"].asInt();
string str = myJson["name"].asString();
4、json數組
Json::Value myjson = getJsonFromFile(“test.json”);//利用上面的函數生成一個json。
int i = 0;
Json::Value arr = myjson[i]; //獲取arr數組的第一個元素
5、利用迭代器獲取json的key。(有時候並不知道json的key,這個時候可以利用迭代器獲取json的key)
Json::Value myjson = getJsonFromFile(“test.json”);//利用上面的函數生成一個json。
Json::Value::Members members(myjson.getMemberNames());
for (Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it) {
const std::string &key = *it;
}
6、自己拼裝Json數組,(有時候發往服務器的數據是一個json數據)
Json::Value arr;
for(int i = 0 ;i < 5;++i){
Json::Value myjson = getJsonFromFile(“test.json”);//利用上面的函數生成一個json。
arr.append(protocolData);
}
如果想讓這個jsonArr有key。
Json::Value arr2;
arr2["array"] = arr;
