C#:从JSON结构中提取/检索子节点

Bei*_*Dev 4 c# json json.net

我们如何从C#中的JSON结构中提取或检索子节点值.

我的应用程序使用OpenWeatherMap,我需要检索的名字城市,临时列表,并描述天气节点,我的JSON和类结构都低于

{
  "cod": "200",
  "message": 0.0284,
  "city": {
    "id": 2643743,
    "name": "London",
    "coord": {
      "lon": -0.12574,
      "lat": 51.50853
    },
    "country": "GB",
    "population": 0,
    "sys": {
      "population": 0
     }
  },
  "cnt": 1,
  "list": [
    {
      "dt": 1429268400,
      "temp": {
        "day": 12.21,
        "min": 4.86,
        "max": 13.18,
        "night": 4.86,
        "eve": 11.76,
        "morn": 12.21
      },
      "pressure": 1028.8,
      "humidity": 66,
      "weather": [
         {
           "id": 803,
           "main": "Clouds",
           "description": "broken clouds",
           "icon": "04d"
        }
      ],
      "speed": 5.9,
      "deg": 67,
      "clouds": 80
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

C#类

public class WeatherForeCast
{
    public string City { get; set; }
    public decimal Day { get; set; }
    public decimal Min { get; set; }
    public decimal Max { get; set; }
    public decimal Night { get; set; }
    public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我熟悉使用JSON.net将C#对象序列化和反序列化为具有完全相同结构的JSON.

And*_*ker 15

如果您只想填充实例WeatherForecast,可以SelectToken在平原上使用几个调用JObject:

var parsed = JObject.Parse(json);
var forecast = new WeatherForeCast();

forecast.City = parsed.SelectToken("city.name").Value<string>();
forecast.Day = parsed.SelectToken("list[0].temp.day").Value<decimal>();
forecast.Description = parsed.SelectToken("list[0].weather[0].description").Value<string>();
forecast.Min = parsed.SelectToken("list[0].temp.min").Value<decimal>();
forecast.Max = parsed.SelectToken("list[0].temp.max").Value<decimal>();
forecast.Night = parsed.SelectToken("list[0].temp.night").Value<decimal>();
Run Code Online (Sandbox Code Playgroud)

请注意,这是非常脆弱的,它正在对JSON的内容做出假设.如果JSON发生更改,则各种属性的路径SelectToken将不正确,此代码将引发异常.