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].ID
、properties[x].PropertyName
和 properties[x].key 在 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());
}