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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With