DataContractJsonSerializer and Enums

后端 未结 5 1685
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 22:42

When I serialize a enum value using DataContractJsonSerializer, it serializes the numerical value of the enum, not the string name.

IE:

enum foo
{
          


        
5条回答
  •  没有蜡笔的小新
    2020-12-05 23:14

    It looks like this is by design and this behavior cannot be changed:

    Enumeration member values are treated as numbers in JSON, which is different from how they are treated in data contracts, where they are included as member names.

    Here's an example using an alternative (and IMO better and more extensible) serializer which achieves what you are looking for:

    using System;
    using Newtonsoft.Json;
    
    class Program
    {
        static void Main(string[] args)
        {
            var baz = Foo.Baz;
            var serializer = new JsonSerializer();
            serializer.Converters.Add(new JsonEnumTypeConverter());
            serializer.Serialize(Console.Out, baz);
            Console.WriteLine();
        }
    }
    
    enum Foo
    {
        Bar,
        Baz
    }
    
    public class JsonEnumTypeConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(Foo);
        }
        public override void WriteJson(JsonWriter writer, object value)
        {
            writer.WriteValue(((Foo)value).ToString());
        }
    
        public override object ReadJson(JsonReader reader, Type objectType)
        {
            return Enum.Parse(typeof(Foo), reader.Value.ToString());
        }
    }
    

提交回复
热议问题