Qt使用QJsonDocument,QJsonObject,QJsonArray解析JSON [英] Qt parsing JSON using QJsonDocument, QJsonObject, QJsonArray

查看:2912
本文介绍了Qt使用QJsonDocument,QJsonObject,QJsonArray解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Qt5.我正在尝试从json对象获取值.这是我试图从中获取数据的json对象的样子:

I'm using Qt5. I am trying to obtain values from a json object. Here is what the json object looks like that I am trying to get data from:

{
    "success": true,
    "properties": [
        {
            "ID": 1001,
            "PropertyName": "McDonalds",
            "key": "00112233445566778899aabbccddeeff"
        },
        {
            "ID": 1002,
            "PropertyName": "Burger King",
            "key": "10112233445566778899aabbccddeeff"
        },
        {
            "ID": 1003,
            "PropertyName": "Taco Bell",
            "key": "20112233445566778899aabbccddeeff"
        }
    ]
}

如何在Qt中创建包含properties[x].IDproperties[x].PropertyNameproperties[x].key的三个数组?

How can I create three arrays that contain properties[x].ID, properties[x].PropertyName, and properties[x].key in Qt?

使用QScriptEngine我尝试了此操作:

QString data = (QString)reply->readAll();

QScriptEngine engine;

QScriptValue result = engine.evaluate(data);

qDebug() << result.toString();

Debug说"SyntaxError:解析错误"

Debug is saying "SyntaxError: Parse error"

推荐答案

我知道了:

QStringList propertyNames;
QStringList propertyKeys;
QString strReply = (QString)reply->readAll();
QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
QJsonObject jsonObject = jsonResponse.object();
QJsonArray jsonArray = jsonObject["properties"].toArray();

foreach (const QJsonValue & value, jsonArray) {
    QJsonObject obj = value.toObject();
    propertyNames.append(obj["PropertyName"].toString());
    propertyKeys.append(obj["key"].toString());
}

这篇关于Qt使用QJsonDocument,QJsonObject,QJsonArray解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆