使用JSON.net将枚举容器序列化为字符串
问题描述:
您可以通过添加属性来将WebAPI模型中的枚举字段序列化为字符串:
You can serialize an enum field in an WebAPI model as a string by adding an attribute:
enum Size
{
Small,
Medium,
Large
}
class Example1
{
[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
Size Size { get; set; }
}
这将序列化为此JSON:
This will serialize to this JSON:
{
"Size": "Medium"
}
如何为枚举集合完成相同的操作?
How can I accomplish the same for a collections of enums?
class Example2
{
IList<Size> Sizes { get; set; }
}
我想序列化为该JSON:
I want to serialize to this JSON:
{
"Sizes":
[
"Medium",
"Large"
]
}