In your Enum just add the EnumMember attribute which specify the value for serialization/deserialization process.
public enum UserType
{
President,
VicePresident,
[EnumMember(Value = "chump")]
Citizen // Chump maps to Citizen, now.
}
The property userType will be Citizen when, in your json, the userType property is equal to "Chump" or "Citizen".
Remember to add the System.Runtime.Serialization reference to your project.
Edit
I noticed that the check of the Value property of EnumMember attribute is case-sensitive. So you can't use "Chump" if in your json you have "chump". To solve this problem you can use a custom StringEnumConverter.
public class UserTypeEnumConverter : StringEnumConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var userTypeType = typeof(UserType);
if (objectType == userTypeType)
{
var value = reader.Value.ToString().ToLower();
foreach (var item in Enum.GetNames(userTypeType))
{
var memberValue = GetEnumMemberValue(userTypeType.GetMember(item)[0]);
if (memberValue != null && memberValue.ToLower() == value)
{
return Enum.Parse(userTypeType, item);
}
}
}
return base.ReadJson(reader, objectType, existingValue, serializer);
}
}
private static string GetEnumMemberValue(MemberInfo memberInfo)
{
var attributes = memberInfo.GetCustomAttributes(typeof(EnumMemberAttribute), inherit: false);
if (attributes.Length == 0) return null;
return ((EnumMemberAttribute)attributes[0]).Value;
}
In the above code, I check only the EnumMember attribute because the UserType's members case-insensitive check is already done by the default StringEnumConvert.
Note that this converter will work only for your UserType enum beacuse of the check:
var userTypeType = typeof(UserType);
if (objectType == userTypeType)
{
Replace the JsonSerializerSettings initialization with:
internal static JsonSerializerSettings JsonSerializerSettings => new JsonSerializerSettings
{
Converters = new JsonConverter[]
{
new UserTypeEnumConverter()
},
Formatting = Formatting.Indented
};
I assumed that Vice-President enumerator is VicePresident in UserType.