【问题标题】:How do I deserialize a json with nested array in c# using Newtonsoft.Json如何使用 Newtonsoft.Json 在 c# 中反序列化带有嵌套数组的 json
【发布时间】:2021-01-18 22:51:42
【问题描述】:

我是 C# 新手。我正在尝试创建一个控制台天气应用程序。我从 OpenWeather API 获取 JSON 数据,如下所示:

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

我已致电JsonConvert.DeserializeObject<WeatherInfo>(stringResult);

我可以反序列化 coord 部分,但是 weather 部分是一个数组,我该如何反序列化它?

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

【问题讨论】:

  • public Weather[] Weather { get; set; }?
  • @gunr2171 我看了,但请放心。
  • Fildor 做对了。如果您的 JSON 属性是一个数组,您需要将您的 c# 属性视为一个集合(数组、列表、IEnumerable、ICollection 等)。
  • @Fildor 明白。我刚刚关闭了一个帐户,因为我的问题不够好。对于已经被编程语言淹没的新手来说,这可能会非常令人沮丧,你知道吗?
  • @Fildor 谢谢,你太棒了。感谢您清除这一切。

标签: c#


【解决方案1】:

使用public Weather[] Weather { get; set; } 进行映射。您的 JSON 的 C# Object Equivalent 将是这样的

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

【讨论】:

    猜你喜欢
    • 2017-08-25
    • 2018-02-10
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    相关资源
    最近更新 更多