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;

最初のデバッグでは、itemObject に記録されたすべての QByteArray の内容が表示され、2 番目のデバッグでは何も表示されません。

それ以外の場合はこれを解析する必要がありますか、またはこのメソッドが機能しないのはなぜですか?

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 にそのタイプを尋ね、それに応じて対応する必要があります。配列、int などの正当なオブジェクトに変換する前に、QJsonValue の型を確認することをお勧めします。

于 2014-11-13T13:59:46.420 に答える
1

特にqt APIには詳しくありませんが、一般的に、JSONオブジェクトはJSON配列でない限り強制的に配列にすることはできません(例:「アイテム」の値)。

おそらく、次のようなものが必要です。

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