我想在QT中解析JSON。JSON看起来像这样:
{
"result": "ok",
"phrase": "katze",
"tuc": [
{
"meaningId": -6468009888908805000,
"meanings": [
{
"text": "common name for animals",
"language": "eng"
}
],
"phrase": {
"text": "cats",
"language": "eng"
}
},
{
"meaningId": -1913936533709497000,
"phrase": {
"text": "felis catus",
"language": "eng"
}
},
{
"meaningId": 8369732998154311000,
"phrase": {
"text": "jack",
"language": "eng"
}
}
],
"from": "deu"
}
我使用下面的代码:
void Slovari::fileIsReady( QNetworkReply * reply)
{
QByteArray rawData = reply->readAll();
QJsonDocument doc(QJsonDocument::fromJson(rawData));
QJsonObject jsonObject = doc.object();
QVariantMap mainmap = jsonObject.toVariantMap();
QVariantList phraseList = mainmap["tuc"].toList();
}
所以我得到了"tuc"数组的变体列表。一般来说,我想获得所有对象的关键字"短语"和他们的值,这是这个数组的内容。有办法把它弄出来吗?或者这对QVariantList不起作用?
解决方案可以是
QVariantList phrases;
Q_FOREACH (const QVariant &v, phraseList) {
QVariantMap m = v.toMap();
if (m.contains("phrase")) {
phrases << m["phrase"].toMap();
}
}