Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize enum as a string in JSON.NET using attributes

Tags:

json

c#

json.net

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

like image 325
shashwat Avatar asked Apr 30 '12 16:04

shashwat


People also ask

Can JSON serialize enums?

By default, enum values are serialized to JSON as integers.

How do you serialize an enum?

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.

How can we send enum value in JSON?

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 .

Is enum serializable C#?

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.


1 Answers

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.

like image 116
Sascha Avatar answered Oct 19 '22 05:10

Sascha