OfirD
OfirD

Reputation: 10490

Custom resolver is ignored when trying to serialize an Exception

I'd like to serialize an Exception using a custom resolver.

Here's an example custom resolver - which should serialize only specified properties:

public class IncludeSpecifiedPropsResolver : DefaultContractResolver
{
    string[] propsToSerialize = null;
    public IncludeSpecifiedPropsResolver(params string[] propsToSerialize)
    {
        this.propsToSerialize = propsToSerialize;
    }
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var allProps = base.CreateProperties(type, memberSerialization);
        if (propsToSerialize == null || propsToSerialize.Length == 0)
        {
           return allProps;
        }
        return allProps.Where(p => propsToSerialize.Contains(p.PropertyName)).ToList();
    }
}

Example usage:

string test = JsonConvert.SerializeObject(new Exception("Something went wrong"), new JsonSerializerSettings()
{
    ContractResolver = new IncludeSpecifiedPropsResolver("Message")
}); 

However, CreateProperties is ignored.

What else is missing so that the custom resolver would work as expected?

Upvotes: 2

Views: 52

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129777

The problem here is that Exception implements the ISerializable interface, which has special handling in the DefaultContractResolver: the code path does not go through CreateProperties(). You can override this behavior by setting the IgnoreSerializableInterface property to true in the constructor of your resolver. If you do this, your code will work as intended.

public IncludeSpecifiedPropsResolver(params string[] propsToSerialize)
{
    this.propsToSerialize = propsToSerialize;
    IgnoreSerializableInterface = true;
}

Working demo: https://dotnetfiddle.net/DNhwaH

Upvotes: 1

Related Questions