Add a custom attribute to json.net

后端 未结 3 1854
温柔的废话
温柔的废话 2021-01-02 10:38

JSON.NET comes with property attributes like [JsonIgnore] and [JsonProperty].

I want to create some custom ones that get run when the seria

3条回答
  •  北海茫月
    2021-01-02 10:56

    You can write a custom contract resolver like this

    public class MyContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver 
                                            where T : Attribute
    {
        Type _AttributeToIgnore = null;
    
        public MyContractResolver()
        {
            _AttributeToIgnore = typeof(T);
        }
    
        protected override IList CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var list =  type.GetProperties()
                        .Where(x => !x.GetCustomAttributes().Any(a => a.GetType() == _AttributeToIgnore))
                        .Select(p => new JsonProperty()
                        {
                            PropertyName = p.Name,
                            PropertyType = p.PropertyType,
                            Readable = true,
                            Writable = true,
                            ValueProvider = base.CreateMemberValueProvider(p)
                        }).ToList();
    
            return list;
        }
    }
    

    You can use it in serialization/deserialization like

    var json = JsonConvert.SerializeObject(
                obj, 
                new JsonSerializerSettings() {
                    ContractResolver = new MyContractResolver()
                });
    
    var obj = JsonConvert.DeserializeObject(
                json, 
                new JsonSerializerSettings() {
                    ContractResolver = new MyContractResolver()
                });
    

提交回复
热议问题