Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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". However, whenever I call JsonConvert.SerializeObject, I end up with

"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. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
357 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...