如何在QML应用中使用Javascript解析JSON

很多QML应需要访问web services。我们可以通过Javascript的方法来解析得到我们所需要的JSON数据,并把它们展示出来。在今天的例子中,我们将展示如何实现它?

我们可以创建一个最基本的“QML App with Simple UI (qmlproject)”,并取名我们的应用为“baidutranslator”。我们将使用的API为:

?client_id=2hG67S2yRm5chkr62j2IEmYL&from=auto&to=auto&q=%E4%BD%A0%E5%A5%BD显示的结果为:{"from":"zh","to":"en","trans_result":[{"src":"\u4f60\u597d","dst":"Hello"}]}我们可以通过这个API的接口来得到中文或英文的翻译,,甚至我们可以得到一个完整句子的中文或英文。上面接口返回的结果是JSON格式的。

为了能够解析我们得到的JSON格式,我们创建了一个“jsonparser.js”文件:

var URL = "?client_id=2hG67S2yRm5chkr62j2IEmYL&from=auto&to=auto&q=";function startParse(keyword, callback) {var doc = new XMLHttpRequest();doc.onreadystatechange = function() {if (doc.readyState == XMLHttpRequest.HEADERS_RECEIVED) {} else if (doc.readyState === XMLHttpRequest.DONE) {if(doc.status != 200) {console.log("!!!Network connection failed!")}else {console.log("got some results!");if(doc.responseText == null) {}else {console.log("result: ", doc.responseText)var json = JSON.parse('' + doc.responseText+ '');json["status"] = "OK";callback.update(json);}}}}doc.open("GET", URL + keyword);doc.send();}

我们通过“startParse”来发送请求,并通过JSON.parse()来解析我们得到的结果。我们通过“callback.update”来返回到我们的QML设计中。

“Main.qml”的设计如下:

import QtQuick 2.0import Ubuntu.Components 1.1import "jsonparser.js" as API/*!\brief MainView with a Label and Button elements.*/MainView {id: root// objectName for functional testing purposes (autopilot-qt5)objectName: "mainView"// Note! applicationName needs to match the "name" field of the click manifestapplicationName: "baidutranslator.liu-xiao-guo"/*This property enables the application to change orientationwhen the device is rotated. The default is false.*///automaticOrientation: true// Removes the old toolbar and enables new features of the new header.useDeprecatedToolbar: falsewidth: units.gu(60)height: units.gu(85)function update(json) {console.log("json: " + JSON.stringify(json));mymodel.clear();if ( json.trans_result !== undefined && json.trans_result.length !== undefined ) {for ( var idx = 0; idx < json.trans_result.length; idx++ ) {if ( json.trans_result[ idx ].dst ) {console.log( 'meaning: ' + json.trans_result[ idx ].dst);mymodel.append( {"meaning": json.trans_result[ idx ].dst });}}} else {mymodel.clear();}}Page {title: i18n.tr("Baidu translator")ListModel {id: mymodel}Column {spacing: units.gu(1)anchors {margins: units.gu(2)fill: parent}TextField {id: inputplaceholderText: "Please input a word"width: parent.widthtext: "你好"onTextChanged: {mymodel.clear();var json = API.startParse(input.text, root);}}Button {id: doitwidth: parent.widthtext: i18n.tr("Translate")onClicked: {var json = API.startParse(input.text, root);}}ListView {id: listviewwidth: parent.widthheight: parent.height – input.height – doit.heightmodel: mymodeldelegate: Text {text: modelData}}}}}这里我们通过“update”来更新我们的ListView。

所有项目的源码是在:git clonehttps://gitcafe.com/ubuntu/baidutranslator.git

风不懂云的漂泊,天不懂雨的落魄,眼不懂泪的懦弱,

如何在QML应用中使用Javascript解析JSON

相关文章:

你感兴趣的文章:

标签云: