Newtonsoft JsonConvert.DeserializeObject how to ignore empty objects

前端 未结 3 1442
栀梦
栀梦 2021-01-05 23:59

I have the following class definitions:

public class Tag
{
    public Guid? TagId { get; set; }
    public string TagText { get; set; }
    public DateTime C         


        
3条回答
  •  借酒劲吻你
    2021-01-06 00:12

    Thanks to @Brian-Rogers's brilliant answer, I was able to come up with a non-generic solution which will work on all collections instead of List only:

    public class IgnoreEmptyArrayItemsConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            bool result = typeof(System.Collections.IEnumerable).IsAssignableFrom(objectType);
            return result;
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var tokenIndexesToRemove = new List();
    
            var array = JArray.Load(reader);
    
            for (int i = 0; i < array.Count; i++)
            {
                var obj = array[i];
                if (!obj.HasValues)
                    tokenIndexesToRemove.Add(i);
            }
    
            foreach (int index in tokenIndexesToRemove)
                array.RemoveAt(index);
    
            var result = array.ToObject(objectType, serializer);
            return result;
        }
    
        public override bool CanWrite
        {
            get { return false; }
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
    

    Instead of looping through the objects, deserializing them and adding them to a hardcoded List collection one by one, this solution will just remove the faulting tokens from the JArray and let the library deserialize the whole array to the type it should be.

    Usage:

    public class Wiki
    {
        ...
        [JsonConverter(typeof(IgnoreEmptyItemsConverter))] // No generic parameter needed
        public HashSet Tags { get; set; }
    }
    

    Fiddle: https://dotnetfiddle.net/9FCcpD

提交回复
热议问题