gpt4 book ai didi

c# - 向 json.net 添加自定义属性

转载 作者:太空狗 更新时间:2023-10-29 20:01:06 25 4
gpt4 key购买 nike

JSON.NET 带有 [JsonIgnore][JsonProperty] 等属性。

我想创建一些在序列化运行时运行的自定义序列,例如[JsonIgnoreSerialize] 或 [JsonIgnoreDeserialize]

我将如何扩展框架以包含它?

最佳答案

您可以像这样编写自定义契约(Contract)解析器

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;
}
}

你可以像这样在序列化/反序列化中使用它

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

var obj = JsonConvert.DeserializeObject<SomeType>(
json,
new JsonSerializerSettings() {
ContractResolver = new MyContractResolver<JsonIgnoreDeserialize>()
});

关于c# - 向 json.net 添加自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32908592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com