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

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

我的应用程序正在使用OpenWeatherMap ,我需要从city检索名称temp列表天气节点的描述 ,我的JSON和Class结构如下

{ "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 } ] } 

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; } } 

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

如果您只想填充WeatherForecast的实例,可以在普通的JObject上使用一些SelectToken调用:

 var parsed = JObject.Parse(json); var forecast = new WeatherForeCast(); forecast.City = parsed.SelectToken("city.name").Value(); forecast.Day = parsed.SelectToken("list[0].temp.day").Value(); forecast.Description = parsed.SelectToken("list[0].weather[0].description").Value(); forecast.Min = parsed.SelectToken("list[0].temp.min").Value(); forecast.Max = parsed.SelectToken("list[0].temp.max").Value(); forecast.Night = parsed.SelectToken("list[0].temp.night").Value(); 

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

使用json2csharp.com生成您的类。

 public class Coord { public double lon { get; set; } public double lat { get; set; } } public class Sys { public int population { get; set; } } public class City { public int id { get; set; } public string name { get; set; } public Coord coord { get; set; } public string country { get; set; } public int population { get; set; } public Sys sys { get; set; } } public class Temp { public double day { get; set; } public double min { get; set; } public double max { get; set; } public double night { get; set; } public double eve { get; set; } public double morn { 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 List { public int dt { get; set; } public Temp temp { get; set; } public double pressure { get; set; } public int humidity { get; set; } public List weather { get; set; } public double speed { get; set; } public int deg { get; set; } public int clouds { get; set; } } public class RootObject { public string cod { get; set; } public double message { get; set; } public City city { get; set; } public int cnt { get; set; } public List list { get; set; } } 

然后使用JSON.NET反序列化到类结构中并提取所需的属性。

 var jsonObject = JsonConvert.DeserializeObject(jsonString); 

您现在有一个RootObject实例,您可以根据需要遍历它以提取您需要的特定值。