本文介绍了如何在json.net中将空字符串反序列化为枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将json属性反序列化为一个枚举,但是当该属性为空字符串时,在处理案例时遇到了问题.

I am deserializing json properties into an enum but I'm having issues handling cases when the property is an empty string.

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

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类和枚举...

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而不是抛出运行时错误?

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?

推荐答案

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

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
}

这篇关于如何在json.net中将空字符串反序列化为枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 14:34