How to Ignoring Fields and Properties Conditionally During Serialization Using JSON.Net?

后端 未结 2 503
迷失自我
迷失自我 2020-12-09 18:04

How to Ignoring Fields and Properties Conditionally During Serialization Using JSON.Net? I can\'t inherit from JsonIgnoreAttribute because it\'s a sealed<

相关标签:
2条回答
  • 2020-12-09 18:19

    I found the answer. I inherit from JsonConverter and create a new convertor.

    public class CustomJsonConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var list = (IList)value;
    
            JArray s = new JArray();
    
            foreach (var item in list)
            {
                JToken token = JToken.FromObject(item);
                JObject obj = new JObject();
    
                foreach (JProperty prop in token)
                {
                    if (prop.Name != "Title") // your logic here
                        obj.Add(prop);
                }
    
                s.Add(obj);
            }
    
            s.WriteTo(writer);
    
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
        }
    
        public override bool CanRead
        {
            get { return false; }
        }
    
        public override bool CanConvert(Type objectType)
        {
            return objectType != typeof(IList);
        }
    }
    
    0 讨论(0)
  • 2020-12-09 18:39

    You can use JSON.NET's ShouldSerialize-syntax. There's a good example on JSON.NET site:

    http://www.newtonsoft.com/json/help/html/ConditionalProperties.htm

    public class Employee
    {
        public string Name { get; set; }
        public Employee Manager { get; set; }
    
        public bool ShouldSerializeManager()
        {
            // don't serialize the Manager property if an employee is their own manager
            return (Manager != this);
        }
    }
    

    If ShouldSerialize doesn't fit your needs, you can take full control of the serialization with the ContractResolvers: http://www.newtonsoft.com/json/help/html/ContractResolver.htm

    0 讨论(0)
提交回复
热议问题