Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QT5 JSON parsing from QByteArray

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?

like image 368
Sergey Proskurnya Avatar asked Mar 17 '23 21:03

Sergey Proskurnya


1 Answers

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.

like image 98
TheDarkKnight Avatar answered Mar 27 '23 19:03

TheDarkKnight