简体   繁体   中英

How do I deserialize a json with nested array in c# using Newtonsoft.Json

I am new to C#. I ma trying to create a console weather app. I have fetched JSON data from OpenWeather API which looks like this:

  "coord": {
    "lon": 27.5667,
    "lat": 53.9
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ],

I have called JsonConvert.DeserializeObject<WeatherInfo>(stringResult);

I am able to deserialize the coord part, however the weather part is an array, how do I deserialize it?

private class WeatherInfo
        {
            public Coord Coord { get; set; }

            public Weather Weather { get; set; }
        }

        private class Weather
        {
            public readonly string Id;
            public readonly string Main;
            public readonly string Description;
            public readonly string Icon;

            public Weather(string lat, string lon, string id, string main, string description, string icon)
            {
                Id = id;
                Main = main;
                Description = description;
                Icon = icon;
            }
        }
        
        private class Coord
        {
            public readonly string Lat;
            public readonly string Lon;

            public Coord(string lat, string lon)
            {
                Lat = lat;
                Lon = lon;
            }
        }
        ```

Use public Weather[] Weather { get; set; } public Weather[] Weather { get; set; } public Weather[] Weather { get; set; } to map.The C# Object Equivalent of your JSON will be like this

public partial class Temperatures
{
    [JsonProperty("coord")]
    public Coord Coord { get; set; }

    [JsonProperty("weather")]
    public Weather[] Weather { get; set; }
}

public partial class Coord
{
    [JsonProperty("lon")]
    public double Lon { get; set; }

    [JsonProperty("lat")]
    public double Lat { get; set; }
}

public partial class Weather
{
    [JsonProperty("id")]
    public long Id { get; set; }

    [JsonProperty("main")]
    public string Main { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }

    [JsonProperty("icon")]
    public string Icon { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM