如何使用json.net将枚举序列化为其他属性名称 [英] How to serialize enums to different property name using json.net

查看:83
本文介绍了如何使用json.net将枚举序列化为其他属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下枚举

public enum PermissionType
{
  [JsonProperty(PropertyName = "can_fly")]
  PermissionToFly,
  [JsonProperty(PropertyName = "can_swim")]
  PermissionToSwim
};

和具有此属性的类

[JsonProperty(PropertyName = "permissions", ItemConverterType = typeof(StringEnumConverter))]
public IList<PermissionType> PermissionKeynames { get; set; }`

我想将枚举列表序列化为字符串列表,并且该序列化列表使用PropertyName中指定的字符串(例如"can_swim")而不是属性的实际名称"PermissionToSwim".但是,每当我调用JsonConvert.SerializeObject时,我都会得到

I want to serialize the list of enumerations to a list of strings, and that serialize list use the string specified in PropertyName (such as "can_swim") instead of the property's actual name "PermissionToSwim". However, whenever I call JsonConvert.SerializeObject, I end up with

"permission_keynames":["PermissionToFly","PermissionToSwim"]

而不是我想要的

"permission_keynames":["can_fly","can_swim"]

我想保留短语"PermissionToSwim"以在我的代码中使用,序列化为另一个单词.知道我该如何实现吗?我的直觉说,注释是罪魁祸首,但我一直找不到正确的注释.

I want to keep the phrase "PermissionToSwim" for use in my code, serialize to another word. Any idea how I can achieve this? My gut says that the annotation is the culprit, but I haven't been able to find the correct one.

推荐答案

EnumMember属性(位于System.Runtime.Serialization中).

Looks like you can make this work using the EnumMember attribute (found in System.Runtime.Serialization).

public enum PermissionType
{
    [EnumMember(Value = "can_fly")]
    PermissionToFly,

    [EnumMember(Value = "can_swim")]
    PermissionToSwim
}

如果使用这些属性,则也不需要在列表的JsonProperty属性中设置ItemConverterType.

If you use those attributes you should also not need to set the ItemConverterType in the JsonProperty attribute on the list.

这篇关于如何使用json.net将枚举序列化为其他属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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