为什么不能通过在qt中解析这个json?

时间:2016-12-09 15:58:09

标签: c++ qt qt5

使用qt5并尝试解析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 个答案:

答案 0 :(得分: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();