如何讀取一個本地Json檔案並查詢該檔案展示其內容
我前一段時間在我的部落格裡寫了一篇文章“如何在QML應用中讀寫檔案”,那篇文章是介紹如何使用C++來讀取檔案的。那種方法是一個比較通用的方法。但是對於有些應用來說,我們可以通過配置JSON來建立我們的UI,或者對不同的平台進行配置,而不用寫一個單獨的設定檔案來做這件事。那麼我們如何不需要通過C++的方法來讀取Json檔案呢?
我們可以使用我們的SDK建立一個最基本的QML應用。為了能夠讀取Json檔案,我們建立一個叫做“jsonparser.js”的檔案:
/* Based on: * 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) * https://github.com/s3u/JSONPath *///Qt.include("jsonpath.js")function readJsonFile(source, callback) { var xhr = new XMLHttpRequest; xhr.open("GET", source); xhr.onreadystatechange = function() { if (xhr.readyState == XMLHttpRequest.DONE) { var doc = xhr.responseText;// console.log("JSON: " + json) var json = JSON.parse(doc); callback.update(json); } } xhr.send();}
我們通過XMLHttpRequest來完成本地檔案的請求工作,並使用callback中的update來傳人到QML檔案中進行解析。為了能夠更加方便地解析我們得到的Json檔案,我們使用了
www.bkjia.com
裡提供的庫。我們可以把“jsonpath.js”下載到我們項目的根目錄下,以方便使用。具體的使用方法可以在網上查看。
為了顯示我們的JSO資料,我們對我們的Main.qml進行了修改:
import QtQuick 2.0import Ubuntu.Components 1.1import "jsonparser.js" as APIimport "jsonpath.js" as JSONPath/*! \brief MainView with a Label and Button elements.*/MainView { id: main // objectName for functional testing purposes (autopilot-qt5) objectName: "mainView" // Note! applicationName needs to match the "name" field of the click manifest applicationName: "readjsonfile.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("it is called in update!"); // we can start to interpret the returned json var authors = JSONPath.jsonPath(json, "$.store.book[*].author"); console.log("length: " + authors.length); for (var i in authors ) { console.log("author[" + i +"] " + authors[i]); mymodel.append( { "content": authors[i], "type": "Authors" }); } // Get all of the books var books = JSONPath.jsonPath(json, "$.store.book[*].title"); console.log("length: " + books.length); for (var j in books ) { console.log("author[" + j +"] " + books[j]); mymodel.append( { "content": books[j], "type": "Books" }); } } Page { id: mainPage title: i18n.tr("Read Json File") ListModel { id: mymodel } Component { id: sectionHeading Rectangle { width: mainPage.width height: childrenRect.height color: "lightsteelblue" Text { text: section font.bold: true font.pixelSize: 20 } } } ListView { id: listview anchors.fill: parent model: mymodel delegate: Text { text: content } section.property: "type" section.criteria: ViewSection.FullString section.delegate: sectionHeading } Component.onCompleted: { console.log("Start to read JSON file"); API.readJsonFile("sample.json", main) } }}
為了完成我們的實驗,我們也建立了一個sample.json檔案。內容如下:
{ "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 } }}
運行我們的應用,我們應用顯示的結果如下: