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