简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM