Json.net contractResolver正在失败

时间:2019-03-08 04:12:16

标签: json json.net

我已经实现了自定义合同解析器,以从序列化的Json中删除一些属性。下面的代码大多数时候都可以工作,但有时此代码会失败。有时它会遍历列表,并跳过我要排除的项目,从而导致出现我要排除的属性。

class TestClass
{
    public static void Test()
    {
        var objectToSerialise = //Coming from some WebAPI calls
        string[] stringToSkip = {"skip1", "skip2"};
        var settings = new JsonSerializerSettings
        {
            ContractResolver = new MyContractResolver(stringToSkip)
        };
        var json = JsonConvert.SerializeObject(objectToSerialise, settings);
    }   
}



public class MyContractResolver : DefaultContractResolver {

    private string[] _skipthis;

    public MyContractResolver(string[] skipthis)
    {
        _skipthis = skipthis;
    }

    private  JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization){
        var property = base.CreateProperty(member, memberSerialization);

        property.ShouldSerialize = (prop) =>{
            return !(_skipthis.Where(n => property.PropertyName.Contains(n)).Any());
        };
        return property;
    }
}

有人可以建议为什么这段代码会间歇性地失败,而不会抛出任何异常吗?

请注意,skipthis数组不会在此之外进行修改。当属性名存在或属性名的子字符串存在于skipthis数组中时,我想跳过该属性。

0 个答案:

没有答案