JSON.NET comes with property attributes like [JsonIgnore]
and [JsonProperty]
.
I want to create some custom ones that get run when the seria
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()
});