如何在json.net中处理空字符串反序列化为枚举

时间:2013-11-20 18:58:38

标签: c# json.net deserialization

我将json属性反序列化为枚举,但是当属性为空字符串时,我遇到处理案例的问题。

  

将值“”转换为输入'EnrollmentState'

时出错

我正在尝试反序列化state中的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课程和枚举...

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
}

如何为反序列化设置默认值,以便将空字符串反序列化为EnrollmentState.Incomplete而不是抛出运行时错误?

1 个答案:

答案 0 :(得分:19)

如果您需要,则需要实现自定义StringEnumConverter

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
}