Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 923
pghprogrammer4 Avatar asked Oct 15 '14 20:10

pghprogrammer4


People also ask

Can JSON serialize enums?

In C#, JSON serialization very often needs to deal with enum objects. By default, enums are serialized in their integer form. This often causes a lack of interoperability with consumer applications because they need prior knowledge of what those numbers actually mean.

How do you serialize an enum?

To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant's name method. To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the java.

How are enums represented in JSON?

JSON has no enum type. The two ways of modeling an enum would be: An array, as you have currently. The array values are the elements, and the element identifiers would be represented by the array indexes of the values.

How does Jackson deserialize enum?

All the methods annotated by @JsonCreator are invoked by Jackson for getting an instance of the enclosing class. In order to deserialize the JSON String to Enum by using the @JsonCreator, we will define the forValues() factory method with the @JsonCreator annotation. We have the following JSON string to deserialize: {


1 Answers

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.

like image 185
Andrew Whitaker Avatar answered Sep 28 '22 05:09

Andrew Whitaker