json.net带有属性属性,如[JsonIgnore][JsonProperty]
我想创建一些自定义的,当序列化运行时运行的,例如。
[JsonIgnoreSerialize]或[JsonIgnoreDeserialize]
我将如何扩展框架以包含此内容?

最佳答案

你可以像这样写一个自定义的合同解析程序

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

08-25 21:38
查看更多