2

I have this Json object and I want to access the "duration" and show it on console using 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"
   }
  }
 ]
}

And my Qt code is this :

{
    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;
}

However my output is :

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(undefined)

v3 = ""

So v1 is fine but v2 becomes undefined.What am I doing wrong and how can I access the "duration" item correctly?

Just_a_guy
  • 25
  • 1
  • 4

2 Answers2

3

The direct answer as follows:

// 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();

The result: PT58M21S

Lion King
  • 32,851
  • 25
  • 81
  • 143
1

items is a list, so calling toObject() on it just returns the default value. According to the documentation:

Converts the value to an object and returns it.

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

You need to be calling toArray() on it, which will convert it to a QJsonArray. From there you can take the first item from the array using a variety of methods, or iterate over the array if that makes more sense for your schema.

MrEricSir
  • 8,044
  • 4
  • 30
  • 35