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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With