gpt4 book ai didi

wcf - DataContractJsonSerializer 和枚举

转载 作者:IT老高 更新时间:2023-10-28 12:47:32 28 4
gpt4 key购买 nike

当我使用 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());
}
}

关于wcf - DataContractJsonSerializer 和枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/794838/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com