将 json 个字符反序列化为 TsEnum

Deserialize json character as TsEnum

我有一个 TsEnum class 用于存储我所有的枚举值。我只是在列表中添加了一个额外的值,但它不会反序列化字符串。所有其他枚举值反序列化都很好,只是不是我刚添加的最新枚举值。

代码

var x  = (SentencePartModelBase)JsonConvert.DeserializeObject(value.ToString(), type);

字符串反序列化

{{
  "Type": 204,
  "Units": {
    "Id": "41",
    "Name": "mg",
    "GroupName": "1"
  },
  "SequenceOrder": 2,
  "IsInvalid": true
}}

[TsEnum]

public enum MaxDoseUnits
{
    [EnumDisplayName("international units")]
    [EnumGroupName("2")]
    [EnumDictionaryId("f4ac115b-5bb1-4653-83af-3a4bef9a80e1")]
    [EnumOrder("")]
    Iu = 41,
}

只需将 [EnumMember(Value = "Id")] 属性添加到枚举

var x  = JsonConvert.DeserializeObject<Root>(json);

public enum MaxDoseUnits
{
    [EnumMember(Value = "Iu")]

    [EnumDisplayName("international units")]
    [EnumGroupName("2")]
    [EnumDictionaryId("f4ac115b-5bb1-4653-83af-3a4bef9a80e1")]
    [EnumOrder("")]
    Iu = 41
}
public class Units
{
    public MaxDoseUnits Id { get; set; }
    public string Name { get; set; }
    public string GroupName { get; set; }
}

public class Root
{
    public int Type { get; set; }
    public Units Units { get; set; }
    public int SequenceOrder { get; set; }
    public bool IsInvalid { get; set; }
}

为了测试,你可以反序列化这个json也没有任何问题

{
  "Type": 204,
  "Units": {
    "Id": "Iu",   //or "Id":41, works too
    "Name": "mg",
    "GroupName": "1"
  },
  "SequenceOrder": 2,
  "IsInvalid": true
}