在QML應用中使用JSONListModel來幫我們解析JSON資料,jsonlistmodeljson

來源:互聯網
上載者:User

在QML應用中使用JSONListModel來幫我們解析JSON資料,jsonlistmodeljson

我們知道JSON資料在很多web service中被廣泛使用。它在我以前的文章中都有被提到:


- 如何讀取一個本地Json檔案並查詢該檔案展示其內容

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


在今天的這篇文章中,我來介紹一種類似像XmlListModel(解析XML)的方法來解析我們的JSON。這個方法更加簡單直接。關於JSONListModel的介紹可以參照地址https://github.com/kromain/qml-utils。


我們今天就利用JSONListModel的網址提供的常式來做說明。


我們首先來看一看JSONListModel的寫法:


JSONListModel.qml


/* JSONListModel - a QML ListModel with JSON and JSONPath support * * Copyright (c) 2012 Romain Pokrzywka (KDAB) (romain@kdab.com) * Licensed under the MIT licence (http://opensource.org/licenses/mit-license.php) */import QtQuick 2.0import "jsonpath.js" as JSONPathItem {    property string source: ""    property string json: ""    property string query: ""    property ListModel model : ListModel { id: jsonModel }    property alias count: jsonModel.count    onSourceChanged: {        var xhr = new XMLHttpRequest;        xhr.open("GET", source);        xhr.onreadystatechange = function() {            if (xhr.readyState == XMLHttpRequest.DONE)                json = xhr.responseText;        }        xhr.send();    }    onJsonChanged: updateJSONModel()    onQueryChanged: updateJSONModel()    function updateJSONModel() {        jsonModel.clear();        if ( json === "" )            return;        var objectArray = parseJSONString(json, query);        for ( var key in objectArray ) {            var jo = objectArray[key];            jsonModel.append( jo );        }    }    function parseJSONString(jsonString, jsonPathQuery) {        var objectArray = JSON.parse(jsonString);        if ( jsonPathQuery !== "" )            objectArray = JSONPath.jsonPath(objectArray, jsonPathQuery);        return objectArray;    }

在這裡,我們可以學習一些如何封裝一個模組並使得我們的model被外界所使用。這個模組的寫法很值得推薦。對於一些大型的軟體來說,我們可以通過這樣的方法來獨立完成我們的model,並被其它模組而使用。可以實現UI和資料的分割。


首先,這個模組定義了一個source屬性。當source一旦被設定後,onSourceChanged將被自動調用,從而發出請求去得到資料。當資料得到後, json的數值發生改變,進而onJsonChanged將被自動調用。最終在updateJSONModel()中,模組所定義的jsonModel將被更新,以被外面的ListView或其它的Control所使用。同樣,每當query發生改變後,model的資料也將被重新修改。


就像我之前的例子一樣,它使用了jsonpath.js模組來實現xpath的查詢功能。


在常式裡,我們可以直接使用JSONListModel來為我們的ListView填充資料:


import QtQuick 2.0import Ubuntu.Components 1.1/*!    \brief MainView with a Label and Button elements.*/MainView {    // objectName for functional testing purposes (autopilot-qt5)    objectName: "mainView"    // Note! applicationName needs to match the "name" field of the click manifest    applicationName: "test1.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(100)    height: units.gu(75)    Page {        title: i18n.tr("test1")        Column {            spacing: units.gu(1)            anchors {                margins: units.gu(2)                fill: parent            }            Label {                id: label                objectName: "label"                text: i18n.tr("Hello..")            }            Button {                objectName: "button"                width: parent.width                text: i18n.tr("Tap me!")                onClicked: {                    label.text = i18n.tr("..world!")                }            }        }    }}


jsonData.txt

{ "store": {    "book": [      { "category": "reference",        "author": "Nigel Rees",        "title": "Sayings of the Century",        "price": 8.95      },      { "category": "fiction",        "author": "Evelyn Waugh",        "title": "Sword of Honour",        "price": 12.99      },      { "category": "fiction",        "author": "Herman Melville",        "title": "Moby Dick",        "isbn": "0-553-21311-3",        "price": 8.99      },      { "category": "fiction",        "author": "J. R. R. Tolkien",        "title": "The Lord of the Rings",        "isbn": "0-395-19395-8",        "price": 22.99      }    ],    "bicycle": {      "color": "red",      "price": 19.95    }  }}



通過不同的查詢,我們可以得到JSON資料中不同條件下的資料。應用的展示效果如下:




項目的源碼在: git clone https://gitcafe.com/ubuntu/jsonlistmodeltest.git



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.