2013-11-20 70 views
11

我反序列化json屬性到一個枚舉,但我遇到問題處理的情況下,當屬性是一個空字符串。如何處理json.net中的空字符串到枚舉的反序列化

錯誤轉換價值 「」 輸入 'EnrollmentState'

我想反序列化的requiredItemstate財產。

{ 
    "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而不是拋出一個運行時錯誤的?

+0

你能不能只爲空字符串添加一個處理程序到EnrollmentState枚舉? – Maess

回答

17

您需要實現定製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 
} 
+2

使用NewtonSoft-6.0.5,enum反序列化不區分大小寫。 「不完整」,因爲json值將成功反序列化爲EnrollmentSate.Incomplete,但不包含任何轉換器。 序列化仍然是一個問題。 –

相關問題