wcf – DataContractJsonSerializer和Enums

前端之家收集整理的这篇文章主要介绍了wcf – DataContractJsonSerializer和Enums前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我使用DataContractJsonSerializer序列化枚举值时,它序列化枚举的数值,而不是字符串名称

IE:

enum foo
{
   bar,baz
}

序列化foo.bar的值返回“0”,而不是“bar”。

我更喜欢它的方式,有没有办法覆盖这个?

编辑:

因为我不想改变串行器,我使用了一个简单的解决方法

我暴露了一个属性在类中序列化调用ToString的值,即:

// 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,且此行为无法更改:

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.

这里有一个使用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());
    }
}

猜你在找的Json相关文章