JSON内容:
{"desc":"OK","status":1000,"data":{"wendu":"-5","ganmao":"昼夜温差较大,较易发生感冒,请适当增减衣服。体质较弱的朋友请注意防护。","forecast":[{"fengxiang":"北风","fengli":"4-5级","high":"高温 -3℃","type":"晴","low":"低温 -10℃","date":"24日星期天"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 2℃","type":"晴","low":"低温 -7℃","date":"25日星期一"},{"fengxiang":"无持续风向","fengli":"3-4级","high":"高温 2℃","type":"晴","low":"低温 -9℃","date":"26日星期二"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 2℃","type":"多云","low":"低温 -6℃","date":"27日星期三"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 4℃","type":"晴","low":"低温 -4℃","date":"28日星期四"}],"yesterday":{"fl":"5-6级","fx":"北风","high":"高温 -11℃","type":"晴","low":"低温 -14℃","date":"23日星期六"},"aqi":"50","city":"北京"}}
QString Json = 上面的JSON内容; QByteArray byte_array; QJsonParseError json_error; QJsonDocument parse_doucment = QJsonDocument::fromJson(byte_array.append(Json),&json_error); if(json_error.error == QJsonParseError::NoError) { QJsonObject obj = parse_doucment.object(); <span style="white-space:pre"> </span>/*可先用if( obj.contains("desc") )判断一下是否存在"desc"对象然后再take取出对象的值*/ QJsonValue desc = obj.take("desc"); if(desc.toString() != "OK") { qDebug()<<"城市错误\n"; return; } QJsonValue data = obj.take("data"); today.ganmao = data.toObject().take("ganmao").toString(); QJsonValue forecast1 = data.toObject().take("forecast"); QJsonArray forecast2 = forecast1.toArray(); for(int i=0; i<5; i++) { QJsonValue value = forecast2.at(i); QJsonObject object = value.toObject(); forecast[i].fengxiang = object.take("fengxiang").toString(); forecast[i].date = object.take("date").toString(); forecast[i].fengli = object.take("fengli").toString(); forecast[i].high = object.take("high").toString(); forecast[i].low = object.take("low").toString(); forecast[i].type = object.take("type").toString(); } } else { qDebug()<<"Json错误"; return; }
参考:Qt之JSON生成与解析