Serialize enum to string
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());
You can just add the attribute:
[Newtonsoft.Json.JsonConverter(typeof(StringEnumConverter))]
to the enum property that is not serializing as a string.
or if you have a more exotic formattting in mind you could use the attributes as below to tell the JSON serializer to serialise only the property that you have formatted as you wish. Depends a bit on the rest of your implementation. It recognises the DataMember attribute on a property as well.
[JsonObject(MemberSerialization = MemberSerialization.OptOut)]
public class Container
{
public Action Action { get; set; }
[JsonProperty(PropertyName = "Action")]
public string ActionString
{
get
{
return Action.ToString();
}
}
}