wcf - DataContractJsonSerializer 和枚举

当我使用 DataContractJsonSerializer 序列化枚举值时,它会序列化枚举的数值,而不是字符串名称。

IE:

enum foo
{
   bar,
   baz
}

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

我更喜欢它,有没有办法覆盖它?

编辑:

因为我不想更改序列化程序,所以我使用了一个简单的解决方法 hack。

我在类中公开了一个属性来序列化,它在值上调用 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());
    }
}

https://stackoverflow.com/questions/794838/

相关文章:

json - IE9 JSON 数据 "do you want to open or save th

python - 在python中将SQL表作为JSON返回

java - 将元数据添加到 RESTful JSON 响应的最佳实践是什么?

python - 通过url获取json数据并在python中使用(simplejson)

javascript - jQuery.getJSON - 访问控制允许来源问题

php - 如何在预先存在的 SQL 数据库之上使用 Elastic Search?

javascript - 如何计算 openweathermap.org JSON 中返回的摄氏温度

jquery - 带有自定义 HTTP header 字段的 JSON 发布

json - 从 Newtonsoft 的 JSON 序列化器解析 JSON 日期时间

xml - 为什么人们希望将 Json 和 XML 作为输出传递到他们的 REST 接口(inter