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

來源:互聯網
上載者:User

標籤:

很多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.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 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。


  


所有項目的源碼是在:git clone https://gitcafe.com/ubuntu/baidutranslator.git


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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.