C# 从Json文件C获取数据#

C# 从Json文件C获取数据#,c#,.net,json,visual-studio,file,C#,.net,Json,Visual Studio,File,我有这个Json文件: {"id":88319,"dt":1345284000,"name":"Benghazi", "coord":{"lat":32.12,"lon":20.07}, "main":{"temp":306.15,"pressure":1013,"humidity":44,"temp_min":306,"temp_max":306}, "wind":{"speed":1,"deg":-7}, "weather":[ {"id":520,"main":"

我有这个Json文件:

{"id":88319,"dt":1345284000,"name":"Benghazi",
"coord":{"lat":32.12,"lon":20.07},
"main":{"temp":306.15,"pressure":1013,"humidity":44,"temp_min":306,"temp_max":306},
"wind":{"speed":1,"deg":-7},
"weather":[
             {"id":520,"main":"rain","description":"light intensity shower rain","icon":"09d"},
             {"id":500,"main":"rain","description":"light rain","icon":"10d"},
             {"id":701,"main":"mist","description":"mist","icon":"50d"}
          ],
"clouds":{"all":90},
"rain":{"3h":3}}
我通常能读“名字”:“班加西”,但“temp”:306.15我不能读,因为它在“main”里面:{}

我用一种简单的方式阅读,下面是我的C代码:

公共类天空天气
{
字符串路径=@“http://api.openweathermap.org/data/2.5/weather?q=Uberaba,br&单位=公制“;
字符串名;
字符串温度;
公共字符串名称{get{return Name;}set{Name=value;}}
公共字符串Temp{get{return Temp;}set{Temp=value;}}
公共字符串GetTemperature()
{
var json=“”;
尝试
{
json=new WebClient().DownloadString(路径);
}
捕获(例外e)
{
返回e.ToString();
}
字符串文本=(字符串)json;
SkyWeather w=JsonConvert.DeserializeObject(文本);
返回w.temp;
}
}

如何读取它?

假设SkyWeather表示“主”对象中的属性,则需要创建另一个表示包装对象的对象:

public class RootObject
{
    public int id { get; set; }
    public int dt { get; set; }
    public string name { get; set; }
    public SkyWeather main { get; set; }
}
。。。然后:

    RootObject w = JsonConvert.DeserializeObject<RootObject>(text);

    return w.main.temp;
RootObject w=JsonConvert.DeserializeObject(文本);
返回主温度;

我明白了,您已经有了一些代码-那么当您尝试使用它时会发生什么?它会为我返回“0”。什么是
SkyWeather
类定义?请将其放入您的问题中。现在,我看到
temp
仅在JSON的
main
属性中。。。那么,假设您显示的代码是
SkyWeather
类(由于您没有提供声明,所以不清楚),您希望它如何反序列化?您的SkyWeather类如何?SkyWeather中的main应定义为类(包含属性temp),但RootObject中的main中不存在“temp”。
    RootObject w = JsonConvert.DeserializeObject<RootObject>(text);

    return w.main.temp;