Newtonsoft JsonConvert.DeserializeObject how to ignore empty objects

前端 未结 3 1469
栀梦
栀梦 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:27

    You could use a custom JsonConverter to ignore the empty objects during deserialization. Something like this could work:

    class IgnoreEmptyItemsConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType.IsAssignableFrom(typeof(List));
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            List list = new List();
            JArray array = JArray.Load(reader);
            foreach (JObject obj in array.Children())
            {
                if (obj.HasValues)
                {
                    list.Add(obj.ToObject(serializer));
                }
            }
            return list;
        }
    
        public override bool CanWrite
        {
            get { return false; }
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
    

    To use the converter, just add a [JsonConverter] attribute to your Tags property like this:

    public class Wiki
    {
        ...
        [JsonConverter(typeof(IgnoreEmptyItemsConverter))]
        public IEnumerable Tags { get; set; }
    }
    

    Fiddle: https://dotnetfiddle.net/hrAFsh

提交回复
热议问题