通过在属性(德)序列化的控制枚举值格式 [英] Control enum value format during (de)serialization via attributes
问题描述
让我们说我有一个代表或其他东西的枚举:
Let's say I have an enum representing something or other:
public enum ResultState
{
Found,
Deleted,
NotFound
}
在我的序列化JSON,我想这些值序列化为发现
,水涨船高
或NOT_FOUND
分别。 (注:这是的不的驼峰,而是一个完全自定义字符串)
In my serialized json, I'd like these values to be serialized as "found"
, "gone"
or "not_found"
respectively. (Note: this is not camelCase, but rather a totally custom string!)
我使用JSON.NET
我就拥有了一切工作差不多吧 - 枚举在全球范围转换成通过 StringEnumConverter
字符串,但我不能为我的生活中看到如何实现类似上述的东西。
I've got everything working almost right - enums are globally converted to strings via the StringEnumConverter
, however I can't for the life of me see how to achieve something similar to the above.
我最初的想法是在 JsonProperty(...)
属性应用到相关的枚举值,但是这似乎并没有工作!
My initial thoughts were to apply the JsonProperty(...)
attribute to the relevant enum values, however this doesn't seem to work!
我能想到得到这个工作的唯一方法是我自己写的 JsonConverter
从 StringEnumConverter
继承,但也有一些额外的魔法来处理新的 JsonName
属性我ð创建。
The only way I can think of getting this work is to write my own JsonConverter
inheriting from StringEnumConverter
, but with some additional magic to handle a new JsonName
attribute I'd create.
正如你可能想象,我不津津乐道的这个想法。
As you might imagine, I don't relish the idea of this.
我在想,如果你精彩的人可以建议一个更简单的方法吗?
推荐答案
碰巧的是,我得太多整个事情。
As it happens, I was overthinking the whole thing.
我利用了 EnumMember
属性从 System.Runtime。 。序列化
,这伟大的工作。
I made use of the EnumMember
attribute from System.Runtime.Serialization
, which worked great.
下面是我的完整性的新枚举:
Here's my new enum for completeness:
public enum QueryResultState
{
[EnumMember(Value="found")]
Found,
[EnumMember(Value="gone")]
Deleted,
[EnumMember(Value="not_found")]
NotFound
}
不要忘了包括呼叫时 StringEnumConverter
JsonConvert.Serialize (...)
,如序列化JSON.NET以枚举默认整数:
Don't forget to include the StringEnumConverter
when calling JsonConvert.Serialize(...)
, as JSON.NET serializes Enums to Integers by default:
JsonConvert.SerializeObject(someObjectWithAnEnum, new StringEnumConverter());
这篇关于通过在属性(德)序列化的控制枚举值格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!