DataContractJsonSerializer和枚举 [英] DataContractJsonSerializer and Enums

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

问题描述

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

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

IE:

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

推荐答案

它看起来像这样是设计使然,并且无法更改此行为:

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

枚举成员值被处理 作为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天全站免登陆