Search code examples
c#serializationjson.net

Any way to get JsonConvert.SerializeObject to ignore the JsonConverter attribute on a property?


I have a class that I cannot change:

public enum MyEnum {
    Item1 = 0,
    Item2 = 1
}
public class foo {
    [JsonConverter(typeof(StringEnumConverter))]
    public MyEnum EnumTypes {get; set; }
}

Somewhere down the line JsonConvert.SerializeObject serializes the object and because of the JsonConverter attribute, it spits out name of the enum value for the foo.EnumTypes rather than the number.

Is there anyway to get JsonConvert.SerializeObject to ignore the attribute on the EnumTypes property?


Solution

  • This is possible, but the process is a tad involved.

    The basic idea is to create a custom ContractResolver and override its CreateProperty method. Something like so:

    internal sealed class MyContractResolver : DefaultContractResolver
    {
        protected override JsonProperty CreateProperty( MemberInfo member, MemberSerialization memberSerialization )
        {
            var property = base.CreateProperty( member, memberSerialization );
    
            if( member.DeclaringType == typeof( foo ) && property.PropertyType == typeof( MyEnum ) )
            {
                property.Converter = null;
            }
    
            return property;
        }
    }
    

    You'll also need to actually instantiate this class and pass it into your serializer/deserializer. What that looks like depends on exactly how you're doing the serialization, so I can't guarantee a relevant example of how to use it.

    If you're just using the static SerializeObject method:

    JsonConvert.SerializeObject( valueToSerialize, new SerializerSettings { ContractResolver = new MyContractResolver() } );