CreateProperty方法没有被点击

时间:2018-06-07 06:00:33

标签: c# serialization json.net

我想基于字符串列表删除对象的某些属性,因为我将其序列化为JSON。我为此创建了一个自定义的ContractResolver,覆盖了CreateProperty方法。但CreateProperty方法永远不会被击中。可能有什么不对?

public class ShouldSerializeContractResolver : DefaultContractResolver
{
    public new static readonly ShouldSerializeContractResolver Instance =
                                  new ShouldSerializeContractResolver();

    private HashSet<string> ignoreList;

    public ShouldSerializeContractResolver() {
        ignoreList = IgnoreListHandler.Instance.IgnoreList;
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {

        JsonProperty property = base.CreateProperty(member, memberSerialization);

        foreach (var thisIgnoreItem in ignoreList)
        {
            if (property.PropertyName.Contains(thisIgnoreItem))
            {
                property.Ignored = true;
            }
        }

        return property;
    }
}

我这样用:

public class MyClass{

    static JsonSerializerSettings settings = new JsonSerializerSettings()
    {
        ContractResolver = new ShouldSerializeContractResolver()
    };

    public void myMethod (){
        var tempObject = JsonConvert.DeserializeObject(jsonString);
        var desiredJsonString = JsonConvert.SerializeObject(tempObject, settings);
    }
}

如果它会有所帮助,这就是字符串列表如何获得它们的价值:

public class IgnoreListHandler
{
    private static readonly Lazy<IgnoreListHandler> ignoreListHandlerInstance = new Lazy<IgnoreListHandler>(() => new IgnoreListHandler());

    private HashSet<string> propertiesToIgnore = new HashSet<string>();

    private IgnoreListHandler()
    {
        using (MyEntities entities = new MyEntities()) {
            propertiesToIgnore = entities.IgnoreProperties.Select(m => m.PropertyName).ToHashSet<string>();
        }
    }

    public static IgnoreListHandler Instance
    {
        get
        {
            return ignoreListHandlerInstance.Value;
        }
    }

    public HashSet<string> IgnoreList {
        get { return propertiesToIgnore; }
    }

}

0 个答案:

没有答案