问题描述
我有以下枚举
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将枚举序列化为其他属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!