QJsonValue变空了

时间:2018-02-24 16:36:52

标签: c++ qt qt5 qjson qjsonobject

当我向时间API请求获取莫斯科时间时,我在变量中得到空int。 这是代码:

QNetworkReply* reply = manager->get(QNetworkRequest(QUrl("https://yandex.com/time/sync.json?geo=213")));
QEventLoop loop;
connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();

QByteArray data = reply->readAll();
QJsonDocument document = QJsonDocument::fromJson(data);
QJsonObject root = document.object();
qDebug() << data;
qDebug() << root.value("time").toInt();

这是JSON:

{"time":1519489796585,"clocks":{"213":{"id":213,"name":"Moscow","offset":10800000,"offsetString":"UTC+3:00","showSunriseSunset":true,"sunrise":"07:33","sunset":"17:53","isNight":true,"skyColor":"#3f68b2","weather":{"temp":-10,"icon":"ovc","link":"/moscow"},"parents":[{"id":225,"name":"Russia"}]}}}

1 个答案:

答案 0 :(得分:1)

如果修改了数字:1519490351963,这超过了整数的较大值:2147483647,因此没有转换为整数,可能的解决方案是将其转换为double:

// qDebug() << root["time"].toDouble();
qDebug() << root.value("time").toDouble();

另一种可能的解决方案是将其转换为QVariant,然后使用toLongLong()来使用qlonglong,这是一种支持更多位的整数类型。

//qDebug() << root["time"].toVariant().toLongLong();
qDebug() << root.value("time").toVariant().toLongLong();