当我使用DataContractJsonSerializer序列化枚举值时,它序列化枚举的数值,而不是字符串名称。
IE:
enum foo { bar,baz }
序列化foo.bar的值返回“0”,而不是“bar”。
我更喜欢它的方式,有没有办法覆盖这个?
编辑:
因为我不想改变串行器,我使用了一个简单的解决方法。
// Old [DataMember] public EnumType Foo { get { return _foo; } set { _foo = value; } } // New,I still kept the EnumType but I only serialize the string version public EnumType Foo { get { return _foo; } set { _foo = value; } } [DataMember] public string FooType { get { return _foo.ToString(); } private set {} }
It looks like this is by design,且此行为无法更改:
原文链接:https://www.f2er.com/json/288720.htmlEnumeration 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.
这里有一个使用an alternative(和IMO更好和更可扩展)序列化程序的示例,它实现您所寻找的:
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()); } }