C# Enum deserialization with Json.Net: Error converting value to type

前端 未结 3 1112
耶瑟儿~
耶瑟儿~ 2021-01-07 23:23

I\'m using Json.NET to serialize/deserialize some JSON APIs.

The API response have some integer values that map to an Enum defined in the application.

The en

3条回答
  •  清歌不尽
    2021-01-07 23:57

    The only way I see it, you should write your own converter. But half of work is already done in class StringEnumConverter. We can override only ReadJson method

    class Program
    {
        static void Main(string[] args)
        {
            const string json = @"{
                    'Name': 'abc',
                    'Type':'Type4'
                }";
    
            // uncomment this if you want to use default value other then default enum first value
            //var settings = new JsonSerializerSettings();
            //settings.Converters.Add(new FooTypeEnumConverter { DefaultValue = FooType.Type3 });
    
            //var x = JsonConvert.DeserializeObject(json, settings);
    
            var x = JsonConvert.DeserializeObject(json);
        }
    }
    
    public class Foo
    {
        public string Name { get; set; }
    
        public FooType Type { get; set; }
    }
    
    public enum FooType
    {
        Type1,
        Type2,
        Type3
    }
    
    public class FooTypeEnumConverter : StringEnumConverter
    {
        public FooType DefaultValue { get; set; }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            try
            {
                return base.ReadJson(reader, objectType, existingValue, serializer);
            }
            catch (JsonSerializationException)
            {
                return DefaultValue;
            }
        }
    }
    

提交回复
热议问题