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

前端 未结 2 438
旧巷少年郎
旧巷少年郎 2021-01-18 10:46

I have a class that I cannot change:

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


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-18 11:17

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

提交回复
热议问题