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

查看:109
本文介绍了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"
        }
    ]
}

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

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 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天全站免登陆