在QML中将JSON解析为列表视图

3

我正在用QML编写一个小应用程序,用于在listview中显示天气详细信息。我无法获取有关如何解析此复杂JSON的任何信息。我正在尝试在QML中解析它。这是我的JSON:

{
"coord":{
"lon":-0.13,
"lat":51.51
},
"weather":[
{
"id":520,
"main":"Rain",
"description":"light intensity shower rain",
"icon":"09d"
},
{
"id":310,
"main":"Drizzle",
"description":"light intensity drizzle rain",
"icon":"09d"
}
],
"base":"cmc stations",
"main":{
"temp":285.33,
"pressure":1006,
"humidity":82,
"temp_min":284.15,
"temp_max":286.15
},
"wind":{
"speed":7.7,
"deg":210,
"gust":12.9
},
"rain":{
"1h":1.4
},
"clouds":{
"all":75
},
"dt":1453904502,
"sys":{
"type":1,
"id":5091,
"message":0.0047,
"country":"GB",
"sunrise":1453880766,
"sunset":1453912863
},
"id":2643743,
"name":"London",
"cod":200
}

我尝试了这段代码,但它没有起作用。在这段代码中,我发送http请求,尝试解析json并将其显示在列表视图中。
import QtQuick 2.0

Rectangle {
    id: main
    width: 320
    height: 640
    color: 'skyblue'

    ListModel { id: listModelJson }

    Rectangle {
        height: parent.height
        width: parent.width
        ListView {
            id: listViewJson
            x: 0
            y: 0
            width: 600
            height: 592
            delegate: Rectangle {
                width: parent.width
                height: 70
            }
            model: listModelJson
        }
    }

    function getCityName() {
        var request = new XMLHttpRequest()
        request.open('GET', 'http://api.openweathermap.org/data/2.5/weather?q=London&appid=44db6a862fba0b067b1930da0d769e98', true);
        request.onreadystatechange = function() {
            if (request.readyState === XMLHttpRequest.DONE) {
                if (request.status && request.status === 200) {
                    console.log("response", request.responseText)
                    var result = JSON.parse(request.responseText)
                    for (var i in result) {
                        listModelJson.append({
                                                 "name" : result[i].name,
                                                 "cod" : result[i].cod
                                             });
                    }
//                    main.cityName = result.response
                } else {
                    console.log("HTTP:", request.status, request.statusText)
                }
            }
        }
        request.send()
    }

    Component.onCompleted: {
        getCityName()
    }
}

你能告诉我如何解析这个JSON吗?


1
嗯,看起来你只是复制/粘贴了代码,而没有理解它的工作原理。首先看一下ListView的委托 - 它只是一个高度为70像素的矩形。但你希望在这里显示一些文本,对吧?另外,在解析json字符串后,你会得到一个对象,而不是数组。所以遍历其属性是没有意义的。只需从对象中获取数据即可。例如,result.coord.lon将给出经度,result.name将给出城市名称。阅读文档以获取ListView的基本用法示例。 - folibis
感谢您的回复@folibis和宝贵的评论。我应该在矩形中放什么?文本?我就是不明白它是如何工作的。 - karen
2个回答

2
我在谷歌上找到了这个问题,并通过ListModel QML Element的文档解决了它。
也许其他人会发现这很有用: Result 代码:
import QtQuick 2.0

Rectangle {
    width: 400
    height: 200

    ListModel {
        id: cityModel
        ListElement {
            name: "Static Sunny City"
            temp: 31.95
            attributes: [
                ListElement { description: "Tropical" },
                ListElement { description: "Cloudless" }
            ]
        }
    }

    Component {
        id: cityDelegate
        Row {
            spacing: 10
            Text { text: name }
            Text { text: temp + "°C" }
        }
    }

    ListView {
        anchors.fill: parent
        model: cityModel
        delegate: cityDelegate
    }

    Component.onCompleted: {
        cityModel.append({"name": "Append Cold City", "temp": 5.95})
        getCityJSON()
    }

    function getCityJSON() {
        var request = new XMLHttpRequest()
        request.open('GET', 'http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=44db6a862fba0b067b1930da0d769e98', true);
        request.onreadystatechange = function() {
            if (request.readyState === XMLHttpRequest.DONE) {
                if (request.status && request.status === 200) {
                    console.log("response", request.responseText)
                    var result = JSON.parse(request.responseText)
                    cityModel.append({
                        "name": result.name + " " + Date(result.dt * 1000),
                        "temp": result.main.temp
                    })
                } else {
                    console.log("HTTP:", request.status, request.statusText)
                }
            }
        }
        request.send()
    }
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接