19

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?

bflemi3
  • 6,698
  • 20
  • 88
  • 155

1 Answers1

23

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
}
Davor Zlotrg
  • 6,020
  • 2
  • 33
  • 51
  • 2
    With NewtonSoft-6.0.5, enum deserialization is case insensitive. "incomplete" as json value will successfully deserialize to EnrollmentSate.Incomplete without any converter. Serialization still is a problem. – Loul G. Sep 28 '14 at 18:30