在JSON字符串反序列化期间如何忽略数组项 [英] How to ignore an array item during deserialization of JSON string

查看:270
本文介绍了在JSON字符串反序列化期间如何忽略数组项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎很简单,但是我不知道该怎么做.我使用外部api(使用Newtonsoft.JSON)获取JSON结果,问题是设计不佳,这给我留下了一个混合类型的数组,如下所示:

It seems to be very simple, but I just can't figure out how to do it. I use an external api to get JSON results (using Newtonsoft.JSON), problem is a poor design which leaves me with a array with mixed types like this:

{"data":["Monday 13 january", {"id":"1234aa","name":"teamA"},{"id":"1234bb","name":"teamB"}, "Tuesday 14 january", {"id":"1234aa","name":"teamA"}]}

这将导致一个对象,如:

This will result in an object like:

public class RootObject
{
  public List<object> data { get; set; }
}

我想忽略这些日期字符串,并将对象反序列化为类型化数组

I want to ignore those date strings and deserialize the objects into a typed array

public class RootObject
{
   public List<Team> data { get; set; }
}

任何想法如何实现这种行为?

Any idea's how to achieve this kind of behavior?

更新: 也许我不清楚,但是我没有在寻找反序列化后进行som转换的解决方案.我想要一些集成的解决方案,例如使用JsonConverter.

Update: Maybe I wasn't clear about it, but I'm not looking for a solution which does soms transformation after the deserialization. I want some integrated solution, eg with a JsonConverter.

推荐答案

可以使用自定义的JsonConverter.

假设您的班级设置如下:

Assuming that you have your classes set up like this:

public class RootObject
{
    [JsonProperty("data")]
    [JsonConverter(typeof(TeamListConverter))]
    public List<Team> Teams { get; set; }
}

public class Team
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
}

然后,您可以使用此JsonConverter来处理JSON数组的反序列化.这将忽略数组中的所有纯字符串(日期),而仅尝试反序列化对象.

Then you can use this JsonConverter to handle the deserialization of the JSON array. This will ignore all the plain strings (dates) in the array and only try to deserialize the objects.

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)
    {
        JArray array = JArray.Load(reader);
        List<Team> teams = new List<Team>();
        foreach (JToken token in array.Children())
        {
            if (token.Type == JTokenType.Object)
            {
                teams.Add(token.ToObject<Team>());
            }
        }
        return teams;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

这是演示程序:

public class Program
{
    public static void Main(string[] args)
    {
        string json = @"
        {
            ""data"":
            [
                ""Monday 13 january"",
                {
                    ""id"":""1234aa"",
                    ""name"":""teamA""
                },
                {
                    ""id"":""1234bb"",
                    ""name"":""teamB""
                }, 
                ""Tuesday 14 january"", 
                {
                    ""id"":""1234aa"",
                    ""name"":""teamA""
                }
            ]
        }";

        RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);

        foreach (Team t in obj.Teams)
        {
            Console.WriteLine(t.Id + " - " + t.Name);
        }
    }
}

这是输出:

1234aa - teamA
1234bb - teamB
1234aa - teamA

这是您要寻找的吗?

这篇关于在JSON字符串反序列化期间如何忽略数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆