Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 "" to type 'EnrollmentState'

I'm trying to deserialize the state property in a requiredItem.

{
    "currentStage" : "Pre-Approved",
    "stages" : ["Applicant", "Pre-Approved", "Approved", "Enrolled"],
    "requiredItems" : [{
            "id" : 1,
            "name" : "Documents",
            "state" : "" 
        }, {
            "id" : 2,
            "name" : "Eligibility Verification",
            "state" : "complete"
        }, {
            "id" : 3,
            "name" : "Placement Information",
            "state" : "incomplete"
        }
    ]
}

RequiredItem class and enum ...

public class RequiredItem {

    /// <summary>
    /// Gets or sets the identifier.
    /// </summary>
    /// <value>The identifier.</value>
    public string id { get; set; }

    /// <summary>
    /// Gets or sets the name.
    /// </summary>
    /// <value>The name.</value>
    public string name { get; set; }

    /// <summary>
    /// Gets or sets the status.
    /// </summary>
    /// <value>The status.</value>
    [JsonProperty(ItemConverterType = typeof(StringEnumConverter))]
    public EnrollmentState state { get; set; }
}

[JsonConverter(typeof(StringEnumConverter))]
public enum EnrollmentState {

    [EnumMember(Value = "incomplete")]
    Incomplete,

    [EnumMember(Value = "actionNeeded")]
    ActionNeeded,

    [EnumMember(Value = "complete")]
    Complete
}

How can I set a default value for the deserialization so that empty strings will be deserialized into EnrollmentState.Incomplete instead of throwing a runtime error?

like image 853
bflemi3 Avatar asked Nov 20 '13 18:11

bflemi3


1 Answers

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
}
like image 72
Davor Zlotrg Avatar answered Sep 23 '22 22:09

Davor Zlotrg