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



我正在将json属性反序列化为枚举,但在处理属性为空字符串的情况时遇到问题。

将值"转换为类型"EnrollmentState"时出错

我正在尝试反序列化requiredItem中的state属性。

{
    "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,而不是引发运行时错误?

如果需要,您需要实现自定义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
}

相关内容

  • 没有找到相关文章

最新更新