我正在用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吗?
result.coord.lon
将给出经度,result.name
将给出城市名称。阅读文档以获取ListView
的基本用法示例。 - folibis