我有这个Json对象,我想访问"duration"并使用Qt在控制台上显示它:
{
"kind": "youtube#videoListResponse",
"etag": ""cbz3lIQ2N25AfwNr-BdxUVxJ_QY/brZ0pmrmXldPPKpGPRM-8I4dDFQ"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": ""cbz3lIQ2N25AfwNr-BdxUVxJ_QY/PkTW6UN9MH0O2kDApjC3penIiKs"",
"id": "WkC18w6Ys7Y",
"contentDetails": {
"duration": "PT58M21S",
"dimension": "2d",
"definition": "hd",
"caption": "false",
"licensedContent": true,
"projection": "rectangular"
}
}
]
}
我的Qt代码是这样的:
{
QJsonDocument jsonResponse = QJsonDocument::fromJson(message);
results = jsonResponse.object();
QJsonValue v1 = results.value("items");
qDebug() << "v1 = " << v1;
QJsonValue v2 = v1.toObject().value("contentDetails");
qDebug() <<"v2 = " << v2;
QString v3 = v2.toObject().value("duration").toString();
qDebug() << "v3 = " << v3;
}
但是我的输出是:
v1 = QJsonValue(array, QJsonArray([{"contentDetails":{"caption":"false","definition":"hd","dimension":"2d","duration":"PT58M21S","licensedContent":true,"projection":"rectangular"},"etag":"\"cbz3lIQ2N25AfwNr-BdxUVxJ_QY/PkTW6UN9MH0O2kDApjC3penIiKs\","id":"WkC18w6Ys7Y","kind":"youtube#video"}]))
v2 = QJsonValue(未定义)
v3 = "
所以 v1 很好,但 v2 变得未定义。我做错了什么,如何正确访问"持续时间"项目?
直接答案如下:
// Read the file which has the JSON object.
QFile file("jsonString.json");
if(!file.open(QFile::ReadOnly)){
qDebug()<< "Error, Cannot open the file.";
return false;
}
QJsonDocument jsonDoc = QJsonDocument::fromJson(file.readAll());
qDebug()<< jsonDoc.object().value("items").toArray()[0].toObject().value("contentDetails").toObject().value("duration").toString();
结果: PT58M21S
items
是一个列表,因此在其上调用 toObject() 只会返回默认值。根据文档:
将值转换为对象并返回它。
如果 type() 不是 Object,则将返回默认值。
你需要在它上面调用 toArray(),这会将其转换为 QJsonArray。从那里,您可以使用各种方法从数组中获取第一项,或者如果这对您的架构更有意义,则遍历数组。