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.
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.
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.
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.
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: {
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With