Search code examples
c#jsonserializationjson-serialization

Exclude StackTrace when serializing Exception to Json using JsonConvert


I'm using the code below to serialize 'objects' to Json:

    var settings = new JsonSerializerSettings
    {
        DefaultValueHandling = DefaultValueHandling.Ignore,
        NullValueHandling = NullValueHandling.Ignore,
    };
    var ObjectJson = JsonConvert.SerializeObject(obj, settings),

However, when I use this same code to serialize an Exception object, some properties (like StackTrace) are also included:

{
    "StackTrace":"   at SomeFile.cs:line xxx",
    "Message":"Message",
    "Data":{},
    "Source":"Source.Namespace",
    "HResult":-2146233088,
    "MyCustomExceptionProperty":"SomeValue"
}

Is there some general way to exclude specific properties (for specific classes, like Exception) from being serialized into the Json, without having to apply attributes (like [JsonIgnore]) to the original class (like Exception), so I can only get this:

{
    "Message":"Message",
    "MyCustomExceptionProperty":"SomeValue"
}

It would be nice to have a general solution, but I'm also glad when it will only work for the unwanted Exception properties.


Solution

  • You can create contract resolver - just figure out the filter condition you want:

    class Resolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            if(typeof(Exception).IsAssignableFrom(type)) {
                IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
                return props.Where(p => ....... ).ToList();
            }
            return base.CreateProperties(type, memberSerialization);
        }
    }
    

    and use it like this:

        JsonSerializerSettings settings = new JsonSerializerSettings
        {
            ContractResolver = new Resolver()
        };
    
        string json = JsonConvert.SerializeObject(w, settings);