2013-02-05 27 views
2

我想在Qt中制作一个小型的天气应用程序,我正在使用JSON格式的世界天气在线API。我只是做了一个简单的文本部分,并试图打印来自接收的数据JSON供稿。 导入QtQuick 2.0在Qt中使用JSON对象

Rectangle { 
TextInput { 
    width: 240 
    id: city_label 
    text: "Chicago" 
    font.family: "Helvetica" 
    font.pointSize: 12 
    color: "#000000" 
    focus: true 
} 

function abc() 
{ 
var doc = new XMLHttpRequest(); 
doc.onreadystatechange = function() { 
    if (doc.readyState == XMLHttpRequest.DONE) { 
     var jsonObject = eval('(' + doc.responseText + ')'); 
     loaded(jsonObject); 
    } 
} 

doc.open("GET", "http://free.worldweatheronline.com/feed/weather.ashx?q=" + city_label.text + "&format=json&num_of_days=2&key=640bc6c793043201130202"); 
doc.send(); 
} 
function showRequestInfo(text) { 
    log.text = log.text + "\n" + text 
    console.log(text) 
} 

function loaded(jsonObject) 
{ 
    showRequestInfo("cloud:" + jsonObject.data.current_condition[0].cloudcover); 
    showRequestInfo("humidity:" + jsonObject.data.current_condition[0].humidity); 
    showRequestInfo("observation_time:" + jsonObject.data.current_condition[0].observation_time); 
    showRequestInfo("precipMM:" + jsonObject.data.current_condition[0].precipMM); 
    showRequestInfo("pressure:" + jsonObject.data.current_condition[0].pressure); 
    showRequestInfo("temp_C:" + jsonObject.data.current_condition[0].temp_C); 
    showRequestInfo("temp_F:" + jsonObject.data.current_condition[0].temp_F); 
    showRequestInfo("visibility:" + jsonObject.data.current_condition[0].visibility); 
    showRequestInfo("weatherCode:" + jsonObject.data.current_condition[0].weatherCode); 
    showRequestInfo("weatherDesc:" + jsonObject.data.current_condition[0].weatherDesc[0].value); 

    showRequestInfo("weatherIconUrl:" + jsonObject.data.current_condition[0].weatherIconUrl[0].value); 
    image1.source = jsonObject.data.current_condition[0].weatherIconUrl[0].value; 

    showRequestInfo("winddir16Point:" + jsonObject.data.current_condition[0].winddir16Point); 
    showRequestInfo("winddirDegree:" + jsonObject.data.current_condition[0].winddirDegree); 
    showRequestInfo("windspeedKmph:" + jsonObject.data.current_condition[0].windspeedKmph); 
    showRequestInfo("windspeedMiles:" + jsonObject.data.current_condition[0].windspeedMiles); 

    showRequestInfo("Location:" + jsonObject.data.request[0].query); 
} 


width: 800 
height: 1280 

MouseArea { 
    anchors.fill: parent 
    onClicked: { 
     Qt.quit(); 
    } 
} 

Text { 
    id: log 
    width: 360 
    anchors.top: parent.top; 
    anchors.bottom: parent.bottom; 
    anchors.margins: 10 

} 

}

回答

1

与在浏览器中一样,您可以访问QML代码中的本机JSON.parse和JSON.serialize。

0

尝试探索约qjson。它提供了解析和序列化json对象的apis。如果您使用的是Qt 5,那么QJson可能包含在Qt库本身中。

+0

如果你使用Qt5,你应该使用Qt JSON(包含在Qt Core中)而不是qjson(外部库)。 –