如何使用 Qt 访问 JSON 的元素

How to access element of JSON using Qt

我有这个 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 = QJson值(数组, QJson数组([{"contentDetails":{"caption":"false","definition":"hd","dimension":"2d","duration":"PT58M21S","licensedContent":true,"projection":"rectangular"} ,"etag":"\"cbz3lIQ2N25AfwNr-BdxUVxJ_QY/PkTW6UN9MH0O2kDApjC3penIiKs\"","id":"WkC18w6Ys7Y","kind":"youtube#video"}]))

v2 = QJson值(未定义)

v3 = ""

所以 v1 没问题,但 v2 变成了 undefined.What 我做错了吗?我怎样才能正确访问 "duration" 项目?

items 是一个列表,因此在其上调用 toObject() 只是 returns 默认值。根据文档:

Converts the value to an object and returns it.

If type() is not Object, the defaultValue will be returned.

您需要打电话给 toArray() on it, which will convert it to a QJsonArray。从那里,您可以使用各种方法从数组中取出第一项,或者如果这对您的架构更有意义,则迭代数组。

直接回答如下:

// 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