QML中的JSON 处理
在 QML 中处理 JSON 数据是常见的需求,以下是完整的 JSON 处理方法指南:
1. JSON 解析与序列化
从字符串解析 JSON
qml
import QtQml 2.15// JSON 字符串
var jsonString = '{"name": "Alice", "age": 25, "skills": ["QML", "JavaScript"]}';// 解析为 JavaScript 对象
var jsonObj = JSON.parse(jsonString);console.log(jsonObj.name); // 输出: "Alice"
console.log(jsonObj.age); // 输出: 25
console.log(jsonObj.skills); // 输出: ["QML", "JavaScript"]
将对象序列化为 JSON 字符串
qml
var person = {name: "Bob",age: 30,married: false,address: {city: "Beijing",street: "Main St"}
};var jsonStr = JSON.stringify(person);
console.log(jsonStr);
// 输出: '{"name":"Bob","age":30,"married":false,"address":{"city":"Beijing","street":"Main St"}}'
2. 格式化 JSON 输出
qml
// 带缩进的格式化输出
var prettyJson = JSON.stringify(person, null, 2);
console.log(prettyJson);
/*
输出:
{"name": "Bob","age": 30,"married": false,"address": {"city": "Beijing","street": "Main St"}
}
*/
3. 与 QML 数据模型结合
将 JSON 数组转换为 ListModel
qml
import QtQuick 2.15
import QtQuick.Controls 2.15ListView {width: 200; height: 200model: ListModel {id: jsonModel}Component.onCompleted: {var data = JSON.parse('[{"name":"Apple","price":5.99},{"name":"Banana","price":3.50}]');data.forEach(function(item) {jsonModel.append(item);});}delegate: Text { text: model.name + ": $" + model.price }
}
从 XMLHttpRequest 获取 JSON
qml
import QtQuick 2.15
import QtQuick.Controls 2.15Item {function loadJsonData() {var xhr = new XMLHttpRequest();xhr.open("GET", "https://api.example.com/data.json");xhr.onreadystatechange = function() {if (xhr.readyState === XMLHttpRequest.DONE) {if (xhr.status === 200) {var response = JSON.parse(xhr.responseText);console.log("Received data:", response);// 处理数据...} else {console.error("Request failed:", xhr.status, xhr.statusText);}}};xhr.send();}Component.onCompleted: loadJsonData()
}
4. 使用 JSON 作为配置
读取 JSON 配置文件
qml
import QtQuick 2.15
import Qt.labs.settings 1.0Item {property var config: ({})Settings {id: settingsproperty string appConfig: JSON.stringify({theme: "light", fontSize: 12})}Component.onCompleted: {config = JSON.parse(settings.appConfig);console.log("Current theme:", config.theme);}function updateConfig(newConfig) {config = newConfig;settings.appConfig = JSON.stringify(newConfig);}
}
5. 注意事项
-
错误处理:
qml
try {var obj = JSON.parse(malformedJson); } catch (e) {console.error("JSON 解析错误:", e); }
-
性能考虑:
-
大型 JSON 数据解析可能会阻塞 UI
-
考虑在 WorkerScript 中处理大型 JSON
-
-
Qt 版本兼容性:
-
JSON
对象在 Qt 5.0 及以上版本可用 -
对于更早版本,可以使用
Qt.include()
加载 JSON 库
-
-
与 C++ 交互:
cpp
// C++ 端可以将 QVariantMap/QVariantList 传递给 QML QVariantMap data; data["name"] = "Alice"; engine.rootContext()->setContextProperty("cppData", data);
qml
// QML 中直接使用 console.log(cppData.name); // "Alice"
6. 实用工具函数
qml
// 安全的 JSON 解析
function safeParse(jsonStr, defaultValue) {try {return JSON.parse(jsonStr);} catch (e) {console.warn("JSON 解析失败:", e);return defaultValue !== undefined ? defaultValue : null;}
}// 深度合并 JSON 对象
function deepMerge(target, source) {for (var key in source) {if (source[key] instanceof Object && target[key] instanceof Object) {deepMerge(target[key], source[key]);} else {target[key] = source[key];}}return target;
}