Serialize enum to string

Naor picture Naor · Feb 6, 2012 · Viewed 48.1k times · Source

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?

Answer

L.B picture L.B · Feb 6, 2012

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());