【问题标题】:QT5 JSON parsing from QByteArray从 QByteArray 解析 QT5 JSON
【发布时间】:2014-11-13 12:54:38
【问题描述】:

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

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

【问题讨论】:

  • 什么是audioDoc,在哪里声明?
  • @Merlin069 抱歉,只是网站上的一个错字,已更正

标签: c++ parsing qt5 qjson


【解决方案1】:

您要么需要知道格式,要么通过询问对象的类型来解决它。这也是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 等)之前检查它的类型是个好主意。

【讨论】:

    【解决方案2】:

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

    也许你想要类似的东西:

    QJsonObject itemObject = audioDoc.object();
    QJsonObject responseObject = itemObject["response"].toObject();
    QJsonArray itemArray = responseObject["items"].toArray();
    

    【讨论】:

    • 谢谢你,你是对的。但是一定要在最后加上QJsonObject responseObject = itemObject["response"]方法toObject(),它提示我编译:)
    猜你喜欢
    • 2013-06-25
    • 2020-05-21
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    • 2012-10-03
    • 1970-01-01
    相关资源
    最近更新 更多