1

I have implemented the custom contract resolver to remove the some properties from serialized Json. Most of the time below code works but occasionally this code fails. Sometime it loops through the list and skips item I want to exclude which causing to appear that properties which I wanted to exclude.

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

Can someone please suggest why this code is failing silently intermittently with out throwing any kind of exception?

Note that skipthis array is not modified outside this. I want to skip the property when property name exist or substring of propertyname exist in skipthis array.

LilRazi
  • 690
  • 12
  • 33
  • 1) You don't clone the `skipthis` array. Is there a chance that it is getting modified outside the contract resolver? 2) Can you share a [mcve]? 3) Why `StringComparison.CurrentCultureIgnoreCase`? You'll get different results in, say, Turkish than English. `OrdinalIgnoreCase` should be used for serialization. – dbc Mar 08 '19 at 05:55
  • Also, why `n.Contains(property.PropertyName)`? If `skipthis` contains a property `CountSpecified` then you will skip the property `Count` also, right? – dbc Mar 08 '19 at 05:58
  • skipthis array is not modified outside this. I want to skip the property when property name exist or substring of propertyname exist in skipthis array. – LilRazi Mar 08 '19 at 13:36
  • Can you share a [mcve] that shows an example of `objectToSerialise` that reproduces the problem? Without a complete, concrete example we can only guess where the problem might lie. – dbc Mar 12 '19 at 19:47

0 Answers0