I want to serialize enum as string using JSON.NET using attributes similar to [JsonIgnore]
Example class:
enum Gender { Male, Female }
class ABC
{
public Gender { get; set; }
}
If I serialize this using JSON.NET:
var a = new ABC();
var str = JsonConvert.SerializeObject(a);
str
is set to {Gender:0}
and I would prefer {Gender:Male}
.
By default, enum values are serialized to JSON as integers.
In order to serialize Enum, we take the help of ObjectMapper class. We use the writeValueAsString() method of ObjectMapper class for serializing Enum. If we serialize Enum by using the writeValueAsString() method, it will represent Java Enums as a simple string.
All you have to do is create a static method annotated with @JsonCreator in your enum. This should accept a parameter (the enum value) and return the corresponding enum. This method overrides the default mapping of Enum name to a json attribute .
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.
Have a look at [JsonConverter(typeof(StringEnumConverter))]
. Should do what you want.
Edit: http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_Converters_StringEnumConverter.htm provides some info.
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