2015-01-14 79 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