从QByteArray进行QT5 JSON解析

Ser*_*nya 4 c++ parsing qt5 qjson

我有QByteArray,包含此JSON

{"response":
      {"count":2,
         "items":[
             {"name":"somename","key":1"},
             {"name":"somename","key":1"}
]}}
Run Code Online (Sandbox Code Playgroud)

需要解析并获取所需的数据:

  QJsonDocument itemDoc = QJsonDocument::fromJson(answer);
  QJsonObject itemObject = itemDoc.object();
  qDebug()<<itemObject;
  QJsonArray itemArray = itemObject["response"].toArray();
  qDebug()<<itemArray;
Run Code Online (Sandbox Code Playgroud)

第一次调试显示记录在itemObject中的所有QByteArray的内容,第二次调试不显示任何内容。

我是否必须对此进行解析,否则为什么此方法无效?

The*_*ght 5

您要么需要了解格式,要么通过询问对象有关其类型的方式来确定格式。这就是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();
}
Run Code Online (Sandbox Code Playgroud)

如果您不知道格式,则必须询问其类型的每个QJsonObject并做出相应的反应。在将QJsonValue转换为其合法对象(例如array,int等)之前,请先检查其类型。