上一篇介紹了C語言寫的JSON解析庫cJSON的使用:使用cJSON庫解析和構建JSON字符串html
本篇文章介紹,Qt開發環境下QJson庫的使用示例,JSON解析配合API接口,就能夠實現一些有趣的工具了,如全國油價查詢工具,全國天氣查詢,空氣質量查詢,黃曆查詢,生活指數等等實用工具的開發。git
分享幾個免費的API提供平臺:github
示例代碼包含簡單和複雜JSON字符串的解析和構建,Qt工程已經開源在Github和Gitee代碼託管平臺。json
開發平臺基於Qt 5.8 Windows。api
示例的JSON字符串和上一篇使用的是同樣的。數組
JSON解析示例包括:微信
JSON的構建:函數
JSON的解析要對照JSON字符串來理解,關於JSON字符串的介紹,能夠參考JSON簡介工具
首先,解析和構建都要包含以下頭文件:網站
#include <QJsonDocument> #include <QJsonObject> #include <QJsonArray>
這個JSON字符串中HeWeather6鍵的值是一個數組,數組內只有1個JSON對象,這個對象裏又嵌套了幾個JSON對象。
{ "HeWeather6": [{ "basic": { "cid": "CN101010700", "location": "昌平", "parent_city": "北京", "admin_area": "北京", "cnty": "中國", "lat": "40.21808624", "lon": "116.23590851", "tz": "+8.00" }, "update": { "loc": "2019-07-20 10:21", "utc": "2019-07-20 02:21" }, "status": "ok", "now": { "cloud": "96", "cond_code": "104", "cond_txt": "陰", "fl": "28", "hum": "86", "pcpn": "0.0", "pres": "995", "tmp": "25", "vis": "4", "wind_deg": "100", "wind_dir": "東風", "wind_sc": "1", "wind_spd": "4" } }] }
字符串1解析函數
主要是JSON的多層嵌套的解析。
int Parse_HeWeather_Now_Json(void) { QJsonParseError err_rpt; QJsonDocument root_Doc = QJsonDocument::fromJson(he_now_json, &err_rpt);//字符串格式化爲JSON if(err_rpt.error != QJsonParseError::NoError) { qDebug() << "JSON格式錯誤"; return -1; } else //JSON格式正確 { // qDebug() << "JSON格式正確:\n" << root_Doc; QJsonObject root_Obj = root_Doc.object(); QJsonValue weather_Value = root_Obj.value("HeWeather6"); //HeWeather6鍵的值,是一個數組 if(weather_Value.isArray()) //可省略 { QJsonObject weather_Obj = weather_Value.toArray().at(0).toObject(); //HeWeather6數組就含有一個元素0 /* basic鍵信息 */ QJsonObject basic_Obj = weather_Obj.value("basic").toObject(); QString cid = basic_Obj.value("cid").toString(); QString location = basic_Obj.value("location").toString(); QString parent_city = basic_Obj.value("parent_city").toString(); QString cnty = basic_Obj.value("cnty").toString(); QString lat = basic_Obj.value("lat").toString(); QString lon = basic_Obj.value("lon").toString(); QString basic_info = cid + " " + parent_city + " " + cnty + " " + lat + " " + lon; qDebug() << basic_info; /* update鍵信息 */ QJsonObject update_Obj = weather_Obj.value("update").toObject(); QString loc = "當地時間:" + update_Obj.value("loc").toString(); //當地時間 QString utc = "UTC時間:" + update_Obj.value("utc").toString(); //UTC時間 QString status = "解析狀態:" + weather_Obj.value("status").toString(); //"ok" qDebug() << loc + " " + utc + " " + status; /* now鍵信息*/ QJsonObject now_Obj = weather_Obj.value("now").toObject(); QString cond_txt = "白每天氣:" + now_Obj.value("cond_txt").toString(); QString hum = "溼度:" + now_Obj.value("hum").toString(); QString tmp = "溫度:" + now_Obj.value("tmp").toString(); QString wind_dir = "風向:" + now_Obj.value("wind_dir").toString(); QString wind_sc = "風級:" + now_Obj.value("wind_sc").toString(); qDebug() << cond_txt + " " + hum + " " + tmp + " " + wind_dir + " " + wind_sc; } qDebug() << "解析完成!"; } return 0; }
這個字符串和上面那個同樣,都是數組元素是JSON對象,對象的值又是一個JSON對象。
{ "results": [{ "location": { "id": "WX4FBXXFKE4F", "name": "北京", "country": "CN", "path": "北京,北京,中國", "timezone": "Asia/Shanghai", "timezone_offset": "+08:00" }, "now": { "text": "晴", "code": "1", "temperature": "-7" }, "last_update": "2018-12-06T22:05:00+08:00" }] }
字符串2解析函數
int Parse_Seniverse_Now_Json(void) { QJsonParseError err_rpt; QJsonDocument root_Doc = QJsonDocument::fromJson(seniverse_now_json, &err_rpt);//字符串格式化爲JSON if(err_rpt.error != QJsonParseError::NoError) { qDebug() << "JSON格式錯誤"; return -1; } else //JSON格式正確 { // qDebug() << "JSON格式正確:\n" << root_Doc; QJsonObject root_Obj = root_Doc.object(); QJsonValue result_Value = root_Obj.value("results"); if(result_Value.isArray()) { QJsonObject result_Obj = result_Value.toArray().at(0).toObject(); QString last_update = result_Obj.value("last_update").toString(); qDebug() << last_update; /* location鍵的值 */ QJsonObject location_Obj = result_Obj.value("location").toObject(); QString id = location_Obj.value("id").toString(); QString name = location_Obj.value("name").toString(); QString timezone = location_Obj.value("timezone").toString(); QString path = location_Obj.value("path").toString(); QString loc_str = id + " " + name + " " + timezone + " " + path ; qDebug() << loc_str; /* now鍵 */ QJsonObject now_Obj = result_Obj.value("now").toObject(); QString code = "天氣代碼: " + now_Obj.value("code").toString(); QString temperature = "當前溫度:" + now_Obj.value("temperature").toString(); QString text = "天氣:" + now_Obj.value("text").toString(); qDebug() << code << temperature << text; } } return 0; }
{ "results": [{ "location": { "id": "WS10730EM8EV", "name": "深圳", "country": "CN", "path": "深圳,深圳,廣東,中國", "timezone": "Asia/Shanghai", "timezone_offset": "+08:00" }, "daily": [{ "date": "2018-12-06", "text_day": "陰", "code_day": "9", "text_night": "陰", "code_night": "9", "high": "25", "low": "16", "precip": "", "wind_direction": "無持續風向", "wind_direction_degree": "", "wind_speed": "10", "wind_scale": "2" }, { "date": "2018-12-07", "text_day": "陰", "code_day": "9", "text_night": "小雨", "code_night": "13", "high": "20", "low": "15", "precip": "", "wind_direction": "北", "wind_direction_degree": "0", "wind_speed": "15", "wind_scale": "3" }, { "date": "2018-12-08", "text_day": "小雨", "code_day": "13", "text_night": "小雨", "code_night": "13", "high": "17", "low": "12", "precip": "", "wind_direction": "東北", "wind_direction_degree": "45", "wind_speed": "15", "wind_scale": "3" }], "last_update": "2018-12-06T18:00:00+08:00" }] }
字符串3解析函數
int Parse_Seniverse_Forecast_Json(void) { QJsonParseError err_rpt; QJsonDocument root_Doc = QJsonDocument::fromJson(seniverse_forcast_json, &err_rpt);//字符串格式化爲JSON if(err_rpt.error != QJsonParseError::NoError) { qDebug() << "JSON格式錯誤"; return -1; } else //JSON格式正確 { // qDebug() << "JSON格式正確:\n" << root_Doc; QJsonObject root_Obj = root_Doc.object(); QJsonValue result_Value = root_Obj.value("results"); if(result_Value.isArray()) { QJsonObject result_Obj = result_Value.toArray().at(0).toObject(); QString last_update = result_Obj.value("last_update").toString(); qDebug() << last_update; /* location鍵的值 */ QJsonObject location_Obj = result_Obj.value("location").toObject(); QString id = location_Obj.value("id").toString(); QString name = location_Obj.value("name").toString(); QString timezone = location_Obj.value("timezone").toString(); QString path = location_Obj.value("path").toString(); QString loc_str = id + " " + name + " " + timezone + " " + path ; qDebug() << loc_str; /* daily預報天氣3天,數組元素3個*/ QJsonValue daily_Vaule = result_Obj.value("daily"); if(daily_Vaule.isArray()) { for(int idx = 0; idx <= 2; idx++) { QJsonObject daily_Obj = daily_Vaule.toArray().at(idx).toObject(); QString date = " 日期:" + daily_Obj.value("date").toString(); QString text_day =" 白每天氣:" + daily_Obj.value("text_day").toString(); QString high = " 最高溫度:" + daily_Obj.value("high").toString(); QString low = " 最低溫度:" + daily_Obj.value("low").toString(); QString wind_direction = " 風向:" + daily_Obj.value("wind_direction").toString(); QString wind_scale = " 風級:" + daily_Obj.value("wind_scale").toString(); qDebug() << date + text_day + high + low + wind_direction + wind_scale; } } } } return 0; }
包含10個元素的數組。
{ "status": "0", "citye": "changchun", "city": "長春", "citycode": "101060101", "aqi": "50", "data": [{ "add": "長春", "aqi": "50", "pm25": "22", "per": "優", "lv": "1" }, { "add": "食品廠", "aqi": "54", "pm25": "18", "per": "良", "lv": "2" }, { "add": "客車廠", "aqi": "52", "pm25": "20", "per": "良", "lv": "2" }, { "add": "郵電學院", "aqi": "35", "pm25": "24", "per": "優", "lv": "1" }, { "add": "勞動公園", "aqi": "45", "pm25": "19", "per": "優", "lv": "1" }, { "add": "園林處", "aqi": "45", "pm25": "21", "per": "優", "lv": "1" }, { "add": "淨月潭", "aqi": "46", "pm25": "30", "per": "優", "lv": "1" }, { "add": "甩灣子", "aqi": "51", "pm25": "24", "per": "良", "lv": "2" }, { "add": "經開區環衛處", "aqi": "48", "pm25": "25", "per": "優", "lv": "1" }, { "add": "高新區管委會", "aqi": "51", "pm25": "16", "per": "良", "lv": "2" }, { "add": "岱山公園", "aqi": "49", "pm25": "19", "per": "優", "lv": "1" }] }
字符串4解析函數
int Parse_AQI_Json(void) { QJsonParseError err_rpt; QJsonDocument root_Doc = QJsonDocument::fromJson(AQI_json, &err_rpt);//字符串格式化爲JSON if(err_rpt.error != QJsonParseError::NoError) { qDebug() << "JSON格式錯誤"; return -1; } else //JSON格式正確 { // qDebug() << "JSON格式正確:\n" << root_Doc; QJsonObject root_Obj = root_Doc.object(); QString city = root_Obj.value("city").toString(); QString citycode = root_Obj.value("citycode").toString(); QString citye = root_Obj.value("citye").toString(); QString status = root_Obj.value("status").toString(); qDebug() << city + " " + citycode + " " + citye + " " + status; /* data鍵 */ QJsonValue data_Vaule = root_Obj.value("data"); if(data_Vaule.isArray()) { for(int idx = 0; idx <= 10; idx++) { QJsonObject data_Obj = data_Vaule.toArray().at(idx).toObject(); QString add = "地址:" + data_Obj.value("add").toString(); QString aqi = " AQI:" + data_Obj.value("aqi").toString(); QString lv = " 空氣質量等級:" + data_Obj.value("lv").toString(); QString per = " 空氣質量:" + data_Obj.value("per").toString(); QString pm25 = " PM2.5等級:" + data_Obj.value("pm25").toString(); qDebug() << add + aqi + lv + per + pm25; } } } return 0; }
比較簡單一個JSON對象
{ "success": "1", "result": { "timestamp": "1542456793", "datetime_1": "2018-11-17 20:13:13", "datetime_2": "2018年11月17日 20時13分13秒", "week_1": "6", "week_2": "星期六", "week_3": "週六", "week_4": "Saturday" } }
字符串5解析函數
int Parse_BJTime_Json(void) { QJsonParseError err_rpt; QJsonDocument root_Doc = QJsonDocument::fromJson(bj_time_json, &err_rpt);//字符串格式化爲JSON if(err_rpt.error != QJsonParseError::NoError) { qDebug() << "JSON格式錯誤"; return -1; } else //JSON格式正確 { // qDebug() << "JSON格式正確:\n" << root_Doc; QJsonObject root_Obj = root_Doc.object(); QString success = root_Obj.value("success").toString(); /* result鍵 */ QJsonObject result_Obj = root_Obj.value("result").toObject(); QString datetime_1 = result_Obj.value("datetime_1").toString(); QString datetime_2 = result_Obj.value("datetime_2").toString(); QString timestamp = result_Obj.value("timestamp").toString(); QString week_1 = result_Obj.value("week_1").toString(); QString week_2 = result_Obj.value("week_2").toString(); QString week_3 = result_Obj.value("week_3").toString(); QString week_4 = result_Obj.value("week_4").toString(); qDebug() << datetime_1 << datetime_2; qDebug() << week_1 << week_2 << week_3 << week_4; } return 0; }
這種格式的字符串也是標準的JSON字符串,[]表示數組,這個數組內包含了5個字符串:
["北京", "6.78", "7.21", "8.19", "6.45"]
可是這種不是,{}表示對象:
{"北京", "6.78", "7.21", "8.19", "6.45"}
一個數組內包含5個元素,每一個元素又是一個數組,每一個數組又包含5個字符串,屬於數組的嵌套:
{ "status": "0", "msg": "全國各省份汽柴油價格信息", "update": "2019-07-21", "data": [ ["地區", "92號", "95號", "98號", "0號柴油"], ["北京", "6.78", "7.21", "8.19", "6.45"], ["上海", "6.74", "7.17", "7.87", "6.39"], ["江蘇", "6.75", "7.18", "8.06", "6.37"], ["天津", "6.77", "7.15", "8.07", "6.41"] ], "About": "wcc", "Home": "www.wangchaochao.top" }
字符串6解析函數
//解析數組嵌套的JSON字符串 int Parse_Oil_Price_Json(void) { QJsonParseError err_rpt; QJsonDocument root_Doc = QJsonDocument::fromJson(oil_price_json, &err_rpt);//字符串格式化爲JSON if(err_rpt.error != QJsonParseError::NoError) { qDebug() << "JSON格式錯誤"; return -1; } else //JSON格式正確 { // qDebug() << "JSON格式正確:\n" << root_Doc; QJsonObject root_Obj = root_Doc.object(); QString msg = root_Obj.value("msg").toString(); QString update = root_Obj.value("update").toString(); QString status = root_Obj.value("status").toString(); QString About = root_Obj.value("About").toString(); QString Home = root_Obj.value("Home").toString(); qDebug() << msg << update << status << About << Home; /* data鍵解析 */ QJsonValue data_Value = root_Obj.value("data"); if(data_Value.isArray()) //數組中包含5個數組,每一個數組5個字符串元素 { for(int idx = 0; idx <= 4; idx++) { QJsonValue price_Obj = data_Value.toArray().at(idx); if(price_Obj.isArray()) { QString str1 = price_Obj.toArray().at(0).toString();// 每一個元素是一個字符串 QString str2 = price_Obj.toArray().at(1).toString(); QString str3 = price_Obj.toArray().at(2).toString(); QString str4 = price_Obj.toArray().at(3).toString(); QString str5 = price_Obj.toArray().at(4).toString(); qDebug() << str1 << str2 << str3 << str4 << str5 ; } } } } return 0; }
void Create_Simple_JSON(void) { //建立JSON對象 QJsonObject root_Obj; //添加鍵值對,值的類型自動識別,順序不可自定義 root_Obj.insert("CSDN", "https://blog.csdn.net/whik1194"); root_Obj.insert("cnblogs", "https://home.cnblogs.com/u/whik/"); root_Obj.insert("Github", "https://github.com/whik/"); root_Obj.insert("Blog", "https://www.wangchaochao.top/"); root_Obj.insert("status", 1); root_Obj.insert("enable", true); root_Obj.insert("update_time", "20190723"); //建立Json文檔 QJsonDocument root_Doc; root_Doc.setObject(root_Obj); QByteArray root_str = root_Doc.toJson(QJsonDocument::Compact); //緊湊格式 // QByteArray root_str = root_Doc.toJson(QJsonDocument::Indented); //標準JSON格式 QString strJson(root_str); QString strJson(root_str); qDebug() << strJson; }
輸出結果
{ "Blog": "https://www.wangchaochao.top/", "CSDN": "https://blog.csdn.net/whik1194", "Github": "https://github.com/whik/", "cnblogs": "https://home.cnblogs.com/u/whik/", "enable": true, "status": 1, "update_time": "20190723" }
void Create_BJTime_JSON(void) { QJsonObject result_Obj; result_Obj.insert("timestamp", "ok"); result_Obj.insert("datetime_1", "2019-07-21 10:46:57"); result_Obj.insert("datetime_2", "2019年07月21日 10時46分57秒"); result_Obj.insert("week_1", "0"); result_Obj.insert("week_2", "星期日"); result_Obj.insert("week_3", "週日"); result_Obj.insert("week_4", "Sunday"); QJsonObject root_Obj; //添加鍵值對,值的類型自動識別,順序不可自定義 root_Obj.insert("status", "success"); root_Obj.insert("Blog", "www.wangchaochao.top"); root_Obj.insert("result", result_Obj); //建立Json文檔 QJsonDocument root_Doc; root_Doc.setObject(root_Obj); QByteArray root_str = root_Doc.toJson(QJsonDocument::Compact); //緊湊格式 // QByteArray root_str = root_Doc.toJson(QJsonDocument::Indented); //標準JSON格式 // qDebug() << root_str; //中文輸出亂碼 QString strJson(root_str); qDebug() << strJson; }
輸出結果
{ "status": "success", "result": { "timestamp": "ok", "datetime_1": "2019-07-21 10:46:57", "datetime_2": "2019年07月21日 10時46分57秒", "week_1": "0", "week_2": "星期日", "week_3": "週日", "week_4": "Sunday" }, "Blog": "www.wangchaochao.top" }
void Create_Array_Str_JSON(void) { QJsonArray root_Arr; root_Arr.insert(0, "Sunday"); root_Arr.insert(1, "Monday"); root_Arr.insert(2, "Tuesday"); root_Arr.insert(3, "Wednesday"); root_Arr.insert(4, "Thursday"); root_Arr.insert(5, "Friday"); root_Arr.insert(6, "Saturday"); //建立Json文檔 QJsonDocument root_Doc; root_Doc.setArray(root_Arr); QByteArray root_str = root_Doc.toJson(QJsonDocument::Compact); //緊湊格式 // QByteArray root_str = root_Doc.toJson(QJsonDocument::Indented); //標準JSON格式 // qDebug() << root_str; //中文輸出亂碼 QString strJson(root_str); qDebug() << strJson; }
輸出結果
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
void Create_Array_JSON(void) { QJsonObject day0_Obj; QJsonObject day1_Obj; QJsonObject day2_Obj; day0_Obj.insert("date", "2019-07-21"); day0_Obj.insert("cond_txt", "多雲"); day0_Obj.insert("cond_code", "101"); day0_Obj.insert("hum", "23"); day0_Obj.insert("tmp_H", "31"); day0_Obj.insert("tmp_L", "25"); day1_Obj.insert("date", "2019-07-21"); day1_Obj.insert("cond_txt", "陣雨"); day1_Obj.insert("cond_code", "107"); day1_Obj.insert("hum", "44"); day1_Obj.insert("tmp_H", "30"); day1_Obj.insert("tmp_L", "26"); day2_Obj.insert("date", "2019-07-22"); day2_Obj.insert("cond_txt", "晴"); day2_Obj.insert("cond_code", "100"); day2_Obj.insert("hum", "20"); day2_Obj.insert("tmp_H", "33"); day2_Obj.insert("tmp_L", "26"); QJsonArray weather_Arr; weather_Arr.insert(0, day0_Obj); weather_Arr.insert(1, day1_Obj); weather_Arr.insert(2, day2_Obj); QJsonObject root_Obj; root_Obj.insert("status", "ok"); root_Obj.insert("update", "2019-07-21 11:00"); root_Obj.insert("Blog", "www.wangchaochao.top"); root_Obj.insert("weather", weather_Arr); //數組做爲weather鍵的值 //建立Json文檔 QJsonDocument root_Doc; root_Doc.setObject(root_Obj); QByteArray root_str = root_Doc.toJson(QJsonDocument::Compact); //緊湊格式 // QByteArray root_str = root_Doc.toJson(QJsonDocument::Indented); //標準JSON格式 // qDebug() << root_str; //中文輸出亂碼 QString strJson(root_str); qDebug() << strJson; }
輸出結果
{ "status": "ok", "weather": [{ "date": "2019-07-21", "cond_txt": "多雲", "cond_code": "101", "hum": "23", "tmp_H": "31", "tmp_L": "25" }, { "date": "2019-07-22", "cond_txt": "晴", "cond_code": "100", "hum": "20", "tmp_H": "33", "tmp_L": "26" }, { "date": "2019-07-23", "cond_txt": "陣雨", "cond_code": "107", "hum": "45", "tmp_H": "32", "tmp_L": "25" }], "update": "2019-07-21 11:00", "Blog": "www.wangchaochao.top" }
void Create_Array_Nest_JSON(void) { QJsonArray table_Arr = {"地區", "92號汽油", "95號汽油", "98號汽油", "0號柴油"}; QJsonArray bj_Arr = {"北京", "6.78", "7.21", "8.19", "6.45"}; QJsonArray sh_Arr = {"上海", "6.74", "7.17", "7.87", "6.39"}; QJsonArray js_Arr = {"江蘇", "6.75", "7.18", "8.06", "6.37"}; QJsonArray tj_Arr = {"天津", "6.77", "7.15", "8.07", "6.41"}; QJsonArray data_Arr; //數組內嵌套了5個數組 data_Arr.insert(0, table_Arr); data_Arr.insert(1, bj_Arr); data_Arr.insert(2, sh_Arr); data_Arr.insert(3, js_Arr); data_Arr.insert(4, tj_Arr); QJsonObject root_Obj; root_Obj.insert("status", "ok"); root_Obj.insert("msg", "全國各省份汽柴油價格信息"); root_Obj.insert("update", "2019-07-21"); root_Obj.insert("About", "wcc"); root_Obj.insert("Blog", "www.wangchaochao.top"); root_Obj.insert("data", data_Arr); //數組做爲鍵的值 //建立Json文檔 QJsonDocument root_Doc; root_Doc.setObject(root_Obj); QByteArray root_str = root_Doc.toJson(QJsonDocument::Compact); //緊湊格式 // QByteArray root_str = root_Doc.toJson(QJsonDocument::Indented); //標準JSON格式 // qDebug() << root_str; //中文輸出亂碼 QString strJson(root_str); qDebug() << strJson; }
輸出結果
{ "status": "ok", "msg": "全國各省份汽柴油價格信息", "update": "2019-07-21", "data": [ ["地區", "92號汽油", "95號汽油", "98號汽油", "0號柴油"], ["北京", "6.78", "7.21", "8.19", "6.45"], ["上海", "6.74", "7.17", "7.87", "6.39"], ["江蘇", "6.75", "7.18", "8.06", "6.37"], ["天津", "6.77", "7.15", "8.07", "6.41"] ], "About": "wcc", "Blog": "www.wangchaochao.top" }
歡迎關注個人我的博客:www.wangchaochao.top
或微信掃碼關注個人公衆號