4

我有 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中,第二次调试不显示任何内容。

我必须否则解析这个,或者为什么这个方法不起作用?

4

2 回答 2

6

您要么需要知道格式,要么通过询问对象的类型来解决它。这就是为什么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 转换为其合法对象(如数组、int 等)之前检查其类型是个好主意。

于 2014-11-13T13:59:46.420 回答
1

我特别不熟悉 qt API,但通常 JSON 对象不能被强制转换为数组,除非它们是 JSON 数组(例如:“items”的值)。

也许你想要类似的东西:

QJsonObject itemObject = audioDoc.object();
QJsonObject responseObject = itemObject["response"].toObject();
QJsonArray itemArray = responseObject["items"].toArray();
于 2014-11-13T13:21:41.127 回答