[英]QT5 JSON parsing from QByteArray
我有QByteArray,包含這個JSON
{"response":
{"count":2,
"items":[
{"name":"somename","key":1"},
{"name":"somename","key":1"}
]}}
需要解析並獲取所需的數據:
QJsonDocument itemDoc = QJsonDocument::fromJson(answer);
QJsonObject itemObject = itemDoc.object();
qDebug()<<itemObject;
QJsonArray itemArray = itemObject["response"].toArray();
qDebug()<<itemArray;
第一次調試顯示所有QByteArray的內容,記錄在itemObject中,第二次調試不顯示任何內容。
我必須解析這個,或者為什么這個方法不起作用?
您要么需要知道格式,要么通過向對象詢問其類型來解決問題。 這就是QJsonValue具有isArray,toArray,isBool,toBool等功能的原因。
如果您知道格式,可以執行以下操作: -
// 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();
}
如果您不知道格式,則必須詢問每個類型的QJsonObject並做出相應的反應。 在將QJsonValue轉換為其合法對象(如array,int等)之前檢查它的類型是個好主意。
我特別不熟悉qt API,但一般來說JSON對象不能被強制轉換為數組,除非它們是JSON數組(例如:“items”的值)。
也許你想要的東西:
QJsonObject itemObject = audioDoc.object();
QJsonObject responseObject = itemObject["response"].toObject();
QJsonArray itemArray = responseObject["items"].toArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.