在 Qt 中解析嵌套的 JSON 时出现意外结果(数组不存在)

unexpected result in parsing nested json in qt (array does not exist)

本文关键字:结果 意外 数组 不存在 Qt 嵌套 JSON      更新时间:2023-10-16

我是qt的新手,我也在堆栈溢出中搜索过,但我无法得到答案,所以这不是一个重复的帖子,因为所有类似的帖子都有数组[],但在此代码中我没有任何数组我想解析这个复杂的 JSON 文件:

{
"query": {
"lang": "en-US",
"results": {
"channel": {
"units": {
"distance": "mi",
"pressure": "in"
},
"ttl": "60",
"location": {
"city": "city",
"country": "not important",
"region": " kkk"
},
"wind": {
"chill": "99",
"direction": "180",
"speed": "14"
}
}
...(more code)

我想获取 chill 数据,但输出是" ",请帮我在 Qt 中打印 chill 数据

这是我代码的一部分:

QNetworkAccessManager manager;
QNetworkReply *response = manager.get(QNetworkRequest(QUrl(url)));
QEventLoop event;
connect(response, SIGNAL(finished()), &event, SLOT(quit()));
event.exec();
json = response->readAll();
QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());
QJsonObject jsonObj = doc.object();
foreach (const QJsonValue &value, jsonObj) {
QJsonObject jsonobj = value.toObject();
qDebug() <<  jsonobj["chill"].toString();
}

qDebug()<<doc.object();的输出是

D/libuntitled7.so(13258): : ** QJsonObject({"query":{"count":1,"created":"2017-07-06T21:21:16Z","lang":"en-US","results":{"channel":{"astronomy":{"sunrise":"5:48 am","sunset":"8:15 pm"},"atmosphere":{"humidity":"16","pressure":"875.0","rising":"0","visibility":"16.1"},"description":"Yahoo! Weather","image":{"height":"18","link":"http://weather.yahoo.com","title":"Yahoo! Weather","url":"http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif","width":"142"},"item":{"condition":{"code":"31","date":"Fri, 07 Jul 2017 12:30 AM IRDT","temp":"85","text":"Clear"},"description":"<![CDATA[<img src="http://l.yimg.com/a/i/us/we/52/31.gif"/>n<BR/>n<b>Forecast:</b>n<BR /> Fri - Sunny. High: 97Low: 78n<BR /> Sat - Sunny. High: 100Low: 79n<BR /> Sun - Sunny. High: 101Low: 81n<BR /> Mon - Sunny. High: 100Low: 81n<BR /> Tue - Mostly 
D/libuntitled7.so(13258): ..untitled7dialog2.cpp:84 (void Dialog2::on_pushButton_clicked()):

下一个输出是 86

正如我在 @MohammedB.B 上评论的那样,一种方法是手动搜索键,另一种方法是创建一个搜索键的函数,在这种情况下,我呈现第二种形式:

QJsonObject findObject(QString key, QJsonObject object){
if(object.isEmpty())
return QJsonObject();
if(object.keys().contains(key)){
return object;
}
else{
for(const QString& _key: object.keys()){
if(object[_key].isObject()){
const QJsonObject& result = findObject(key, object[_key].toObject());
if(!result.isEmpty()){
return result;
}
}
}
}
return QJsonObject();
}
QJsonValue findValuebyKey(QString key, QJsonDocument doc){
QJsonObject obj_key = findObject(key, doc.object());
return obj_key[key];
}

例:

QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());
qDebug()<<findValuebyKey("chill", doc).toString();

输出:

"99"

注意:如果生成"for"启用 c ++ 11 的问题,可以通过向 .pro 添加CONFIG += c++11来执行此操作

您还需要迭代通道数组。简单的解决方案:

const QJsonDocument doc = QJsonDocument::fromJson(response->readAll().toUtf8());
// Access to "query"
const QJsonObject queryObject = doc.object();
// Access to "results"
const QJsonObject resultsObject = queryObject.value("results").toObject();
// Access to "chanels"
const QJsonObject channelsObject = resultsObject.value("channels").toObject();
// Access to "wind"
const QJsonObject windObject = channelsObject.value("wind").toObject();
// And then access to "chill"
const QJsonValue chill = windObject.value("chill");

最佳做法是创建一个递归函数来递归解析 JSON。