Qt5 JSON parsing from QByteArray

15.5k views Asked by At

I have QByteArray,contains this JSON

{"response":
      {"count":2,
         "items":[
             {"name":"somename","key":1"},
             {"name":"somename","key":1"}
]}}

Need to parse and get the required data:

  QJsonDocument itemDoc = QJsonDocument::fromJson(answer);
  QJsonObject itemObject = itemDoc.object();
  qDebug()<<itemObject;
  QJsonArray itemArray = itemObject["response"].toArray();
  qDebug()<<itemArray;

First debug displays the contents of all QByteArray, recorded in itemObject, second debug does not display anything.

Must i parse this otherwise,or why this method does not work?

2

There are 2 answers

0
TheDarkKnight On

You either need to know the format, or work it out by asking the object about its type. This is why QJsonValue has functions such as isArray, toArray, isBool, toBool, etc.

If you know the format, you can do something like this: -

// get the root object
QJsonDocument itemDoc = QJsonDocument::fromJson(answer);
QJsonObject rootObject = itemDoc.object();

// get the response object
QJsonValue response = rootObject.value("response");
QJsonObject responseObj = response.toObject();

// print out the list of keys ("count")
QStringList keys = responseObj.keys();
foreach(QString key, keys)
{
    qDebug() << key; 
}

// print the value of the key "count")
qDebug() << responseObj.value("count");

// get the array of items
QJsonValue itemArrayValue = responseObj.value("items");

// check we have an array
if(itemArrayValue.isArray())
{
    // get the array as a JsonArray
    QJsonArray itemArray = itemArrayValue.toArray();
}

If you don't know the format, you'll have to ask each QJsonObject of its type and react accordingly. It's a good idea to check the type of a QJsonValue before converting it to its rightful object such as array, int etc.

1
Jeremy E. On

I'm not familiar with qt APIs in particular, but in general JSON objects cannot be coerced into arrays unless they are JSON arrays (ex: the value for "items").

Perhaps you want something like:

QJsonObject itemObject = audioDoc.object();
QJsonObject responseObject = itemObject["response"].toObject();
QJsonArray itemArray = responseObject["items"].toArray();