How to handle deserialization of empty string into enum in json.net

前端 未结 1 752
忘了有多久
忘了有多久 2021-01-04 02:11

I am deserializing json properties into an enum but I\'m having issues handling cases when the property is an empty string.

Error converting value \"\

相关标签:
1条回答
  • 2021-01-04 02:38

    You need to implement custom StringEnumConverter if you want that:

    public class EnrollmentStateEnumConverter : StringEnumConverter
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (string.IsNullOrEmpty(reader.Value.ToString()))
                return EnrollmentState.Incomplete;
    
            return base.ReadJson(reader, objectType, existingValue, serializer);
        }
    }
    
    [JsonConverter(typeof(EnrollmentStateEnumConverter))]
    public enum EnrollmentState
    {
        [EnumMember(Value = "incomplete")]
        Incomplete,
    
        [EnumMember(Value = "actionNeeded")]
        ActionNeeded,
    
        [EnumMember(Value = "complete")]
        Complete
    }
    
    0 讨论(0)
提交回复
热议问题