向json.net添加自定义属性 [英] Add a custom attribute to json.net
本文介绍了向json.net添加自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
JSON.NET带有[JsonIgnore]
和[JsonProperty]
之类的属性.
JSON.NET comes with property attributes like [JsonIgnore]
and [JsonProperty]
.
我想创建一些自定义代码,这些代码可以在序列化运行时运行,例如
[JsonIgnoreSerialize]
或[JsonIgnoreDeserialize]
I want to create some custom ones that get run when the serialisation runs e.g.
[JsonIgnoreSerialize]
or [JsonIgnoreDeserialize]
我将如何扩展该框架以包含此内容?
How would I go about extending the framework to include this?
推荐答案
您可以像这样编写自定义的合同解析器
You can write a custom contract resolver like this
public class MyContractResolver<T> : Newtonsoft.Json.Serialization.DefaultContractResolver
where T : Attribute
{
Type _AttributeToIgnore = null;
public MyContractResolver()
{
_AttributeToIgnore = typeof(T);
}
protected override IList<JsonProperty> 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<JsonIgnoreSerialize>()
});
var obj = JsonConvert.DeserializeObject<SomeType>(
json,
new JsonSerializerSettings() {
ContractResolver = new MyContractResolver<JsonIgnoreDeserialize>()
});
这篇关于向json.net添加自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文