反序列化JSON字典List< CustomType>

本文关键字:CustomType List int JSON 字典 反序列化 | 更新日期: 2023-09-27 18:13:13

我需要将Dictionary类型的JSON字典反序列化为列表(列表),我使用JSON。Net用于此目的。当然,这是一个惊人的图书馆,只是我有点卡住了!

我正在订阅一些API,响应如下所示:

    "team_details": {
                "0": {
                    "index": 1,
                    "team_id": "1..",
                    "team_name": "Research Team",
                    "team_url": "...",
                    "role": "Administrator"
                },
                "1": {
                    "index": 2,
                    "team_id": "2..",
                    "team_name": "WB Team",
                    "team_url": "...",
                    "role": "User"
                }
}

我需要用这个来转换它到List<Team>,其中Teams:

Class Teams{
 public int Index{get;set;}
 public String TeamName{get;set;}
...
}

反序列化JSON字典<int,CustomType>List< CustomType>

最简单的方法是将其反序列化为Dictionary<string, Team>,然后在需要时使用dictionary.Values.ToList()将值放入列表中。

但是,如果您确实希望在类定义中使用List<Team>,则可以使用自定义JsonConverter在反序列化期间进行转换。

public class TeamListConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(List<Team>));
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        return token.Values().Select(v => v.ToObject<Team>()).ToList();
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
演示:

class Program
{
    static void Main(string[] args)
    {
        string json = @"
        {
            ""team_details"": {
                ""0"": {
                    ""index"": 1,
                    ""team_id"": ""1.."",
                    ""team_name"": ""Research Team"",
                    ""team_url"": ""..."",
                    ""role"": ""Administrator""
                },
                ""1"": {
                    ""index"": 2,
                    ""team_id"": ""2.."",
                    ""team_name"": ""WB Team"",
                    ""team_url"": ""..."",
                    ""role"": ""User""
                }
            }
        }";
        RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
        foreach (Team team in root.Teams)
        {
            Console.WriteLine(team.TeamName);
        }
    }
}
public class RootObject
{
    [JsonProperty("team_details")]
    [JsonConverter(typeof(TeamListConverter))]
    public List<Team> Teams { get; set; }
}
public class Team
{
    [JsonProperty("index")]
    public int Index { get; set; }
    [JsonProperty("team_id")]
    public string TeamId { get; set; }
    [JsonProperty("team_name")]
    public string TeamName { get; set; }
    [JsonProperty("team_url")]
    public string TeamUrl { get; set; }
    [JsonProperty("role")]
    public string Role { get; set; }
}
输出:

Research Team
WB Team
相关文章: