How do I deserialize an array of enum using Json.Net?

后端 未结 2 1384
我寻月下人不归
我寻月下人不归 2021-01-17 07:28

I have a JSON like this:

[{ 
    \"agencyId\": \"myCity\",
    \"road\": {
    \"note\": \"\",
        \"lat\": \"45.321\",
        \"lon\": \"12.21\",
              


        
相关标签:
2条回答
  • 2021-01-17 08:13

    The StringEnumConverter expects only a single enumeration value. Because ChangeTypes is an array, you need to annotate the property a little differently to make it work.

    Try this instead:

    [JsonProperty("changeTypes", ItemConverterType=typeof(StringEnumConverter))]
    public ChangeType[] ChangeTypes { get; set; }
    
    0 讨论(0)
  • 2021-01-17 08:21

    There is no need to write a custom JsonConverter for serializing/deserializing array of Enum. Instead of decorating individual property within parent model, just decorate the Enum with a StringEnumConverter JsonConverter attribute.

    For eg:-

    Following Environment model has Shelter enum property and array of enum Shelter[]

    public class Environment
    {
    
        public string Name { get; set; }
        public Shelter Shelter { get; set; }
        public Shelter[] Shelters { get; set; }
    }
    
    [JsonConverter(typeof(StringEnumConverter))]
    public enum Shelter
    {
        Indoor,
        Outdoor
    }
    

    Output json:-

     {
       "name": "",
       "shelter": "Indoor",
        "shelters": [
           "Indoor",
           "Outdoor"
      ]
     }
    
    0 讨论(0)
提交回复
热议问题