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 添加自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:向 json.net 添加自定义属性


- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 使用 rss + c# 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01