2016-12-09 59 views
0

使用QT5並試圖分析JSON爲什麼不能通過qt解析這個json?

這裏的功能:

void MainWindow::parse(QString &json){ 

    QJsonDocument doc(QJsonDocument::fromJson(json.toUtf8())); 
    QJsonObject obj = doc.object(); 
    QJsonArray result = obj["results"].toArray(); 
    QJsonValue location =result.at(0); 
    QJsonValue now = result.at(1); 
    QJsonValue time = result.at(2); 
    cityName = location.toObject().take("name").toString(); 
    status = now.toObject().take("text").toString(); 
    qDebug()<<time.toString(); // this qdebug is for testing 
} 

的JSON的QString看起來是這樣的:

{ 
    "results": [ 
     { 
      "location": { 
       "id": "WX4FBXXFKE4F", 
       "name": "北京", 
       "country": "CN", 
       "path": "北京,北京,中國", 
       "timezone": "Asia/Shanghai", 
       "timezone_offset": "+08:00" 
      }, 
      "now": { 
       "text": "晴", 
       "code": "0", 
       "temperature": "-4" 
      }, 
      "last_update": "2016-12-09T23:25:00+08:00" 
     } 
    ] 
} 

我期待qDebug輸出爲"2016-12-09T23:25:00+08:00",但它只是""

而且citynamestatus竟然設置爲""

這裏有什麼問題?謝謝!

+1

你有沒有檢查'result.size()' ?你是否嘗試通過並檢查'QJsonDocument :: fromJson'中的'QJsonParseError * error'? – Jarod42

+1

用調試器遍歷代碼並檢查變量值。如果你不能通過它來弄明白,那麼在每個語句之間添加調試打印,並用該代碼編輯問題,並且它是完整的輸出。 – hyde

回答

3

在您的JSON字符串中,"results"是一個對象數組,每個對象都有鍵"location","now""last_update"。並且每個"location""now"是用不同的密鑰JSON對象。

您正在訪問的結果對象,如果它是一個數組,你應該使用按鍵,讓你值訪問作爲一個對象正在尋找:

QJsonDocument doc(QJsonDocument::fromJson(jsonByteArray)); 
QJsonObject obj = doc.object(); 
QJsonArray results = obj["results"].toArray(); 
//get the first "result" object from the array 
//you should do this in a loop if you are looking for more than one result 
QJsonObject firstResult= results.at(0).toObject(); 
//parse "location" object 
QJsonObject location= firstResult["location"].toObject(); 
QString locationId= location["id"].toString(); 
QString locationName= location["name"].toString(); 
QString locationCountry= location["country"].toString(); 
QString locationPath= location["path"].toString(); 
QString locationTimeZone= location["timezone"].toString(); 
QString locationTimeZoneOffset= location["timezone_offset"].toString(); 
//parse "now" object 
QJsonObject now= firstResult["now"].toObject(); 
QString nowText= now["text"].toString(); 
QString nowCode= now["code"].toString(); 
QString nowTemperature= now["temperature"].toString(); 
//parse "last_update" 
QString lastUpdate= firstResult["last_update"].toString(); 
相關問題