Serialize a container of enums as strings using JSON.net

前端 未结 2 748
忘了有多久
忘了有多久 2020-11-27 06:10

You can serialize an enum field in an WebAPI model as a string by adding an attribute:

enum Size
{
    Small,
    Medium,
    Large
}

class Example1
{
    [         


        
相关标签:
2条回答
  • 2020-11-27 06:56

    I have this in the startup code of my web app to serialise all enums to strings (I prefer passing enum names to values, makes things more robust).

    Must admit I've never tried it on a list of enums though so I don't know what it would do with that - might be worth a try.

    var jsonFormatter = config.Formatters.JsonFormatter;
    jsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true });
    
    0 讨论(0)
  • 2020-11-27 06:58

    You need to use JsonPropertyAttribute.ItemConverterType property:

    class Example2
    {
        [JsonProperty (ItemConverterType = typeof(StringEnumConverter))]
        public IList<Size> Sizes { get; set; }
    }
    
    0 讨论(0)
提交回复
热议问题