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

前端 未结 2 439
旧巷少年郎
旧巷少年郎 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() } );
    
    0 讨论(0)
  • 2021-01-18 11:29

    I do not believe you can, as it is part of the definition. You'll have to remove the attribute and add the converter to the serializer settings instead:

    var serializerSettings = new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore,
        DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate,
    
        Converters = new List<JsonConverter> { new StringEnumConverter() },
    
        ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
    };
    

    In that case you can omit it if you don't want to use it. There is one thing I forgot to mention, the converter has to check the type in CanConvert:

    public class StringEnumConverter: JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(MyEnum);
        }
    }
    

    I didn't test the code, but you'll get the idea.

    0 讨论(0)
提交回复
热议问题