使用JSON.net将枚举容器序列化为字符串 [英] Serialize a container of enums as strings using JSON.net

查看:49
本文介绍了使用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"
  ]
}

推荐答案

您需要使用

You need to use JsonPropertyAttribute.ItemConverterType property:

class Example2
{
    [JsonProperty (ItemConverterType = typeof(StringEnumConverter))]
    public IList<Size> Sizes { get; set; }
}

这篇关于使用JSON.net将枚举容器序列化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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