2015-01-14 81 views
0

//編輯:這不是重複建議的線程無法幫助我,因爲我的問題涉及到Newton.Json // 我是使用Newtonsoft.Json作爲我的歷史Weatherapp(大學項目)。所以我選擇使用openweathermap.org。在這裏我的代碼:Newton.Json:異常:NullReferenceException天氣數據請求openweathermap

var request = (HttpWebRequest)WebRequest.Create("http://api.openweathermap.org/data/2.5/history/city?q=exampletown&start=1420135249&end=1421085649&type=hour") 
var response = await request.GetResponseAsync(); 
var rawJson = new StreamReader(response.GetResponseStream()).ReadToEnd(); 

var json = JObject.Parse(rawJson); 
string temp_value = json["temp"].ToObject<string>(); 

我總是geting一個異常:NullReferenceException:對象引用未設置爲對象的實例。其他信息:json和rawjson不是null,temp_value是。當我在worng的地方提問時,我很抱歉。我是新來的人。

PS:URI是不是完全地正確,我取代我鎮exampletown

+0

看看json字符串是什麼樣子會很有幫助。 – cgotberg

+0

嘿。嘗試使用此URI:http://api.openweathermap.org/data/2.5/history/city?id=2885679&type=hour&start=1369728000&end=1369789200&type=hour – ad0R

+0

發生異常的位置在哪裏?如果它在'json [「temp」]行中,只要在嘗試訪問它之前檢查'json [「temp」]'是否爲空。這與Newtonsoft.Json無關,這實際上是重複的。如果你想知道爲什麼'json [「temp」]'爲空,請隔離導致問題的json片段。如果您嘗試一次解析所有數據,則永遠不會發現問題,我們也不能 –

回答

0

這可能是因爲返回的JSON沒有一個叫temp屬性。例如,我試着在提琴手1http://api.openweathermap.org/data/2.5/history/city?id=2885679&type=hour&start=1369728000&end=1369789200&type=hour以下API調用,並沒有看到temp屬性。

Json being returned

+0

哦,我明白了。所以我試了一下city_id,換算沒問題。但這不是我想要的結果。我真的需要得到這樣的東西:「temp」:278.241,「temp_min」:278.241,「temp_max」:278.241。當我調用list屬性時,該值仍然爲空。有任何想法嗎? – ad0R

+0

這可能是因爲您正在嘗試將它作爲字符串強制轉換,當您編寫'.ToObject ();' –

+0

您會推薦什麼? – ad0R