Here is the approach that I often use when I encounter the same problem. ( Here is the fiddle , if you want to go straight to the working example)
Enum Settings
I often need alternative values for enumerations. For this reason, I like to create an attribute to store these alternative values. For instance:
[AttributeUsage(AttributeTargets.Field)] public class AlternativeValueAttribute : Attribute { public string JsonValue { get; set; } public string DbValue { get; set; }
(Note that the DbValue property DbValue not relevant for the purposes of this demonstration ... It simply demonstrates the existence of several alternative values.)
And when creating an enum object, I use this attribute for every value that requires an alternative value. For instance:
public enum ObjectState { [AlternativeValue(DbValue = "-1", JsonValue="is-unknown")] Unknown, [AlternativeValue(DbValue = "1", JsonValue="is-active")] Active, [AlternativeValue(DbValue = "0", JsonValue="is-inactive")] Inactive
Create Converter
Now we need to create a converter so that we can use an alternative value. In this case, we serialize / deserialize Json, so we will create a JsonConverter :
public class AlternativeValueJsonConverter<TEnum> : JsonConverter where TEnum : struct, IConvertible, IComparable, IFormattable { public override bool CanConvert( Type objectType ) {
Usage
Usage Finally, to use this JsonConverter , we need to decorate our enum object with it. Thus, the ObjectState enumeration that we have already declared must be updated to use the converter. For instance:
[JsonConverter(typeof(AlternativeValueJsonConverter<ObjectState>))] public enum ObjectState { [AlternativeValue(DbValue = "-1", JsonValue="is-unknown")] Unknown, [AlternativeValue(DbValue = "1", JsonValue="is-active")] Active, [AlternativeValue(DbValue = "0", JsonValue="is-inactive")] Inactive
Now for the demo, we will create a simple POCO that contains an ObjectState enumeration and convert it to Json to make sure that we get the expected results:
public class DemoPoco { public ObjectState MyObjectState { get; set; } } public static void Main( string[] args ) { DemoPoco demo = new DemoPoco { MyObjectState = ObjectState.Active }; var json = JsonConvert.SerializeObject( demo ); Console.WriteLine(json);