JavaScriptSerializer - JSON serialization of enum as string

后端 未结 27 2358
耶瑟儿~
耶瑟儿~ 2020-11-22 03:22

I have a class that contains an enum property, and upon serializing the object using JavaScriptSerializer, my json result contains the integer valu

27条回答
  •  广开言路
    2020-11-22 03:59

    Noticed that there is no answer for serialization when there is a Description attribute.

    Here is my implementation that supports the Description attribute.

    public class CustomStringEnumConverter : Newtonsoft.Json.Converters.StringEnumConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            Type type = value.GetType() as Type;
    
            if (!type.IsEnum) throw new InvalidOperationException("Only type Enum is supported");
            foreach (var field in type.GetFields())
            {
                if (field.Name == value.ToString())
                {
                    var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
                    writer.WriteValue(attribute != null ? attribute.Description : field.Name);
    
                    return;
                }
            }
    
            throw new ArgumentException("Enum not found");
        }
    }
    

    Enum:

    public enum FooEnum
    {
        // Will be serialized as "Not Applicable"
        [Description("Not Applicable")]
        NotApplicable,
    
        // Will be serialized as "Applicable"
        Applicable
    }
    

    Usage:

    [JsonConverter(typeof(CustomStringEnumConverter))]
    public FooEnum test { get; set; }
    

提交回复
热议问题