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

185 篇文章 6 订阅
159 篇文章 2 订阅

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


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


http://openapi.baidu.com/public/2.0/bmt/translate?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 = "http://openapi.baidu.com/public/2.0/bmt/translate?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.0
import Ubuntu.Components 1.1
import "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 manifest
    applicationName: "baidutranslator.liu-xiao-guo"

    /*
     This property enables the application to change orientation
     when the device is rotated. The default is false.
    */
    //automaticOrientation: true

    // Removes the old toolbar and enables new features of the new header.
    useDeprecatedToolbar: false

    width: 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: input
                placeholderText: "Please input a word"
                width: parent.width
                text: "你好"

                onTextChanged: {
                    mymodel.clear();
                    var json = API.startParse(input.text, root);
                }
            }

            Button {
                id: doit
                width: parent.width

                text: i18n.tr("Translate")

                onClicked: {
                    var json = API.startParse(input.text, root);
                }
            }

            ListView {
                id: listview
                width: parent.width
                height: parent.height - input.height - doit.height
                model: mymodel

                delegate: Text {
                    text: modelData
                }

            }
        }
    }
}

这里我们通过“ update”来更新我们的ListView。


  


所有项目的源码是在:https://github.com/liu-xiao-guo/baidutranslator


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值