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

前端 未结 2 472
旧巷少年郎
旧巷少年郎 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: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 { 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.

提交回复
热议问题