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?
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.
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.
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.
Converts an Enum to and from its name string value. Newtonsoft.Json. JsonConverter. Newtonsoft.Json.Converters.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With