C# : extract/retrieve child node from JSON structure

橙三吉。 提交于 2019-12-04 12:56:31

If you just want to populate an instance of WeatherForecast, you could use a few SelectToken calls on a plain 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>();

Note that this is pretty brittle though, it's making assumptions about the contents of the JSON. If the JSON changes, the path to various properties in SelectToken will be incorrect and this code will throw an exception.

Use json2csharp.com to generate your classes.

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> 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> list { get; set; }
}

Then use JSON.NET to deserialize into the class structure and extract the properties you want.

var jsonObject = JsonConvert.DeserializeObject<RootObject>(jsonString);

You now have an instance of RootObject and you can traverse it as needed to extract the specific value(s) you need.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!