I have an enum annotated with EnumMember
to facilitate JSON.NET serialization similar to the following:
[DataContract]
[JsonConverter(typeof(StringEnumConverter))]
public enum Status
{
[EnumMember(Value = "NOT_ADMITTED")]
NotAdmitted,
[EnumMember(Value = "ADMITTED")]
Admitted
}
Now, independent of the JSON.NET serialization I'd like to I'd like to convert instances of the enum to a string while abiding by the EnumMember
annotations in the data contract, e.g.:
aStatusInstance.ToString() == "NOT_ADMITTED"
.
Any suggestions? Thanks!
Update: My Solution
I modified the code in the accepted answer to create an extension method to retrieve the EnumMember Value:
public static string GetEnumMemberValue(this Enum enumValue)
{
var type = enumValue.GetType();
var info = type.GetField(enumValue.ToString());
var da = (EnumMemberAttribute[])(info.GetCustomAttributes(typeof(EnumMemberAttribute), false));
if (da.Length > 0)
return da[0].Value;
else
return string.Empty;
}
I would use the Description Attribute and decorate the enum with the same value as the EnumMember:
[DataContract]
[JsonConverter(typeof(StringEnumConverter))]
public enum Status
{
[EnumMember(Value = "NOT_ADMITTED")]
[Description("NOT_ADMITTED")]
NotAdmitted,
[EnumMember(Value = "ADMITTED")]
[Description("ADMITTED")]
Admitted
}
You can use this code snippet to parse it. This is written as an extension of the Enum class:
public static string GetDescription(this Enum enumValue)
{
Type type = enumValue.GetType();
FieldInfo info = type.GetField(enumValue.ToString());
DescriptionAttribute[] da = (DescriptionAttribute[])(info.GetCustomAttributes(typeof(DescriptionAttribute), false));
if (da.Length > 0)
return da[0].Description;
else
return string.Empty;
}
You can then compare it with the following:
aStatusInstance.GetDescription() == "NOT_ADMITTED"
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