2014-10-29 35 views
0

http://api.openweathermap.org/data/2.5/weather?q=Ankara,tr这是当前的JSON数据,首先我用JSON 2 C#创建它,我得到这个分析JSON与json.net但蹊跷的猜测

using System; 
using System.Collections.Generic; 

namespace weatherSample 
{ 
    public class service 
    { 
     public service() 
     { 
     } 
    } 

    public class Coord 
    { 
     public double lon { get; set; } 

     public double lat { get; set; } 
    } 

    public class Sys 
    { 
     public int type { get; set; } 

     public int id { get; set; } 

     public double message { get; set; } 

     public string country { get; set; } 

     public int sunrise { get; set; } 

     public int sunset { get; set; } 
    } 

    public class Weather 
    { 
     public int id { get; set; } 

     public string main { get; set; } 

     public string description { get; set; } 

     public string icon { get; set; } 
    } 

    public class MainWeather 
    { 
     public double temp { get; set; } 

     public int pressure { get; set; } 

     public int humidity { get; set; } 

     public double temp_min { get; set; } 

     public double temp_max { get; set; } 
    } 

    public class Wind 
    { 
     public double speed { get; set; } 

     public int deg { get; set; } 
    } 

    public class Clouds 
    { 
     public int all { get; set; } 
    } 

    public class RootObject 
    { 
     public Coord coord { get; set; } 

     public Sys sys { get; set; } 

     public List<Weather> weather { get; set; } 

     public string @base { get; set; } 

     public MainWeather main { get; set; } 

     public Wind wind { get; set; } 

     public Clouds clouds { get; set; } 

     public int dt { get; set; } 

     public int id { get; set; } 

     public string name { get; set; } 

     public int cod { get; set; } 
    } 
} 

现在我试图解析,但我得到了一些麻烦,

WebClient webC = new WebClient (link); 

var jsonDatas = JObject.Parse (y); 

var c = JsonConvert.DeserializeObject <MainWeather> (y); 

Console.Write (c.temp); 

则返回0值

应该是什么问题?

回答

1

你需要反序列化到的RootObject一个实例,而不是:

RootObject result = JsonConvert.DeserializeObject<RootObject>(y); 

然后访问MainWeather属性:

Console.Write(result.main.temp); 

例子:https://dotnetfiddle.net/LWfHrH

如果你只是关心MainWeather对象,你也可以这样做:

MainWeather r = JObject.Parse(y)["main"].ToObject<MainWeather>(); 
+0

是的,我很惊讶地发现它,谢谢你的信息btw :),这是所有的json数据吗?需要从顶部使用? – 2014-10-29 20:53:02

+0

@HâlukYilmaz:你的意思是你总是需要反序列化到'RootObject'那样吗? – 2014-10-29 21:03:17

+0

是的,亲爱的安德鲁,对不起,发音不好,我正好试着说出你的意思,因为我从儿童使用之前得到零或0在使用之前 – 2014-10-29 21:04:37