Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize enum to string

I have an enum:

public enum Action {     Remove=1,     Add=2 } 

And a class:

[DataContract] public class Container {     [DataMember]     public Action Action {get; set;} } 

When serialize instance of Container to json I get: {Action:1} (in case Action is Remove).

I would like to get: {Action:Remove} (instead of int I need to ToString form of the enum)

Can I do it without adding another member to the class?

like image 640
Naor Avatar asked Feb 06 '12 07:02

Naor


People also ask

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.

Can you serialize an enum 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.

Can enum implement serializable?

Because enums are automatically Serializable (see Javadoc API documentation for Enum), there is no need to explicitly add the "implements Serializable" clause following the enum declaration.

What is Stringenumconverter?

Converts an Enum to and from its name string value. Newtonsoft.Json. JsonConverter. Newtonsoft.Json.Converters.


Video Answer


1 Answers

Using Json.Net, you can define a custom StringEnumConverter as

public class MyStringEnumConverter : Newtonsoft.Json.Converters.StringEnumConverter {     public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)     {         if (value is Action)         {             writer.WriteValue(Enum.GetName(typeof(Action),(Action)value));// or something else             return;         }          base.WriteJson(writer, value, serializer);     } } 

and serialize as

string json=JsonConvert.SerializeObject(container,new MyStringEnumConverter()); 
like image 116
L.B Avatar answered Sep 21 '22 04:09

L.B