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 添加自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!