[英]How to serialize enums to different property name using json.net
I have the following enum我有以下枚举
public enum PermissionType
{
[JsonProperty(PropertyName = "can_fly")]
PermissionToFly,
[JsonProperty(PropertyName = "can_swim")]
PermissionToSwim
};
and a class with this property和具有此属性的类
[JsonProperty(PropertyName = "permissions", ItemConverterType = typeof(StringEnumConverter))]
public IList<PermissionType> PermissionKeynames { get; set; }`
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".我想将枚举列表序列化为字符串列表,并且该序列化列表使用
PropertyName
中指定的字符串(例如“can_swim”)而不是属性的实际名称“PermissionToSwim”。 However, whenever I call JsonConvert.SerializeObject, I end up with但是,每当我调用 JsonConvert.SerializeObject 时,我都会得到
"permission_keynames":["PermissionToFly","PermissionToSwim"]
instead of my desired而不是我想要的
"permission_keynames":["can_fly","can_swim"]
I want to keep the phrase "PermissionToSwim" for use in my code, serialize to another word.我想保留短语“PermissionToSwim”以在我的代码中使用,序列化为另一个单词。 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.
我的直觉说注释是罪魁祸首,但我找不到正确的注释。
Looks like you can make this work using the EnumMember
attribute (found in System.Runtime.Serialization). 看起来您可以使用
EnumMember
属性(在 System.Runtime.Serialization 中找到)来完成这项工作。
public enum PermissionType
{
[EnumMember(Value = "can_fly")]
PermissionToFly,
[EnumMember(Value = "can_swim")]
PermissionToSwim
}
If you use those attributes you should also not need to set the ItemConverterType
in the JsonProperty
attribute on the list.如果您使用这些属性,您也不需要在列表的
JsonProperty
属性中设置ItemConverterType
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.