DataContractJsonSerializer 和枚举 [英] DataContractJsonSerializer and Enums

查看:22
本文介绍了DataContractJsonSerializer 和枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

浏览器:

enum foo
{
   bar,
   baz
}

序列化 foo.bar 的值返回0",而不是bar".

Serializing a value of foo.bar returns "0", not "bar".

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

I'd prefer it the other way around, is there a way to override this?

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

Because I didn't want to change the serializer, I used a simple workaround hack.

我在类中公开了一个属性来序列化,该属性对值调用 ToString,即:

I exposed a property in the class to serialize that calls ToString on the value, ie:

// 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 {}
}

推荐答案

看起来就像这是设计使然,这种行为无法改变:

枚举成员值被处理作为 JSON 中的数字,这是不同的从它们在数据中的处理方式来看合同,其中包括为会员名.

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.

这是一个使用 替代方案的示例(和 IMO 更好、更可扩展)序列化程序可实现您的需求:

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());
    }
}

这篇关于DataContractJsonSerializer 和枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆