繁体   English   中英

来自QByteArray的QT5 JSON解析

[英]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.

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