How To Serialize Nonstandard Enum Values

Integrating with third-party systems occasionally require enum values that are invalid .NET enum names. This article illustrates how to get around this issue.

Introduction 

.NET client libraries that integrate with third-party APIs occasionally need to compromise on how enum values are represented in model classes. For example, an API that requires values to be expressed in all uppercase letters force the creation of an enum similar to:
  1. public enum YesNoMaybeEnum  
  2.  {  
  3.      YES,  
  4.      NO,  
  5.      MAYBE   
  6.  }  
While this will compile, it violates .NET naming conventions. In other cases, the third party may include names that include invalid characters like dashes or periods. For example, Amazon's Alexa messages include a list of potential request types that include a period in the names. These values cannot be expressed as enumation names. While this could be addressed by changing the data type of the serialized property from an enumeration to a string, the property values are no longer constrained and any suggestions from Intellisense are lost.
 
This article demonstrates how to eat your cake and have it, too. Using attributes and reflection, values can be serialized to and deserialized from JSON.
 
Serialization with EnumDescription
 
Let's say we need to serialize values that include periods. Creating an enum like the following generates compile time errors, 
  1. public enum RequestTypeEnum  
  2. {  
  3.     LaunchRequest,  
  4.     IntentRequest,  
  5.     SessionEndedRequest,  
  6.     CanFulfillIntentRequest,  
  7.     AlexaSkillEvent.SkillPermissionAccepted,  
  8.     AlexaSkillEvent.SkillAccountLinked,  
  9.     AlexaSkillEvent.SkillEnabled,  
  10.     AlexaSkillEvent.SkillDisabled,  
  11.     AlexaSkillEvent.SkillPermissionChanged,  
  12.     Messaging.MessageReceived  
  13. }  
The EnumMember attribute defines the value to serialize when dealing with data contracts. Samples on Stack Overflow that show enumeration serialization tend to use the Description attribute. Either attribute can be used or you can create your own. The EnumMember attribute is more tightly bound to data contract serialization while the Description attribute is for use with design time and runtime environments, the serialization approach in this article opts for the EnumMember. After applying the EnumMember and Data Contract attributes, the enum now looks like,
  1. [DataContract(Name = "RequestType")]    
  2. public enum RequestTypeEnum    
  3. {    
  4.     [EnumMember(Value = "LaunchRequest")]    
  5.     LaunchRequest,    
  6.     [EnumMember(Value = "IntentRequest")]    
  7.     IntentRequest,    
  8.     [EnumMember(Value = "SessionEndedRequest")]    
  9.     SessionEndedRequest,    
  10.     [EnumMember(Value = "CanFulfillIntentRequest")]    
  11.     CanFulfillIntentRequest,    
  12.     [EnumMember(Value = "AlexaSkillEvent.SkillPermissionAccepted")]    
  13.     SkillPermissionAccepted,    
  14.     [EnumMember(Value = "AlexaSkillEvent.SkillAccountLinked")]    
  15.     SkillAccountLinked,    
  16.     [EnumMember(Value = "AlexaSkillEvent.SkillEnabled")]    
  17.     SkillEnabled,    
  18.     [EnumMember(Value = "AlexaSkillEvent.SkillDisabled")]    
  19.     SkillDisabled,    
  20.     [EnumMember(Value = "AlexaSkillEvent.SkillPermissionChanged")]    
  21.     SkillPermissionChanged,    
  22.     [EnumMember(Value = "Messaging.MessageReceived")]    
  23.     MessageReceived    
  24. }    
The EnumMember attribute is also applied to enum members without periods. Otherwise, the DataContractSerilizer would serializes the numeric representation of the enumeration value. Now we can define a DataContract with,
  1. [DataContract]  
  2. public class SamplePoco  
  3. {  
  4.     [DataMember]  
  5.     public RequestTypeEnum RequestType { getset; }  
  6. }  
And serialize it to XML with,
  1. SamplePoco enumPoco = new SamplePoco();  
  2.   
  3. enumPoco.RequestType = RequestTypeEnum.SkillDisabled;  
  4.   
  5. DataContractSerializer serializer = new DataContractSerializer(typeof(SamplePoco));  
  6.   
  7. var output = new StringBuilder();  
  8. using (var xmlWriter = XmlWriter.Create(output))  
  9. {  
  10.   
  11.     serializer.WriteObject(xmlWriter, enumPoco);  
  12.     xmlWriter.Close();  
  13. }  
  14.   
  15. string xmlOut = output.ToString();   
This generates the following XML,
  1. <?xml version="1.0" encoding="utf-16"?><SamplePoco xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/EnumSerializationSample"><RequestType>AlexaSkillEvent.SkillDisabled</RequestType>  
  2. </SamplePoco>  
DataContract serialization is sorted out, but doesn't yet address JSON serialization.
 
JSON Serialization
 
If you need to work with any REST API endpoints, then you'll need to support JSON. The NewtonSoft JSON has its own serialization strategy, and so the EnumMember attribute needs to be leveraged to integrate with it using a custom JsonConverter, but before taking that step, the enumation value must be read from the attribute.
 
This method accepts an enum value and returns the string value in the EnumMember attribute. 
  1. private string GetDescriptionFromEnumValue(Enum value)  
  2.         {  
  3.  
  4. #if NETSTANDARD2_0  
  5.             EnumMemberAttribute attribute = value.GetType()  
  6.                 .GetField(value.ToString())  
  7.                 .GetCustomAttributes(typeof(EnumMemberAttribute), false)  
  8.                 .SingleOrDefault() as EnumMemberAttribute;  
  9.   
  10.             return attribute == null ? value.ToString() : attribute.Value;  
  11. #endif  
  12.  
  13. #if NETSTANDARD1_6 || NETSTANDARD1_3 || NET45 || NET47  
  14.   
  15.             EnumMemberAttribute attribute = value.GetType()  
  16.                 .GetRuntimeField(value.ToString())  
  17.                 .GetCustomAttributes(typeof(EnumMemberAttribute), false)  
  18.                 .SingleOrDefault() as EnumMemberAttribute;  
  19.   
  20.             return attribute == null ? value.ToString() : attribute.Value;  
  21.             
  22. #endif  
  23.   
  24.   
  25.             throw new NotImplementedException("Unsupported version of .NET in use");  
  26.         }  
There's a subtle difference between the .NET Standard 2.0 implementation and the others. In .NET Standard 1.6 and prior versions, use the GetRuntimeField method to get a property from a type. In .NET Standard 2.0, use the GetField method to return the property of a type. The compile-time constants and checks in the GetDescriptionFromEnumValue abstract away that complexity.  
 
Coming the other way, a method needs to take a string and convert it to the associated enumeration.
  1. public T GetEnumValue(string enumMemberText)   
  2. {  
  3.   
  4.     T retVal = default(T);  
  5.   
  6.     if (Enum.TryParse<T>(enumMemberText, out retVal))  
  7.         return retVal;  
  8.   
  9.   
  10.     var enumVals = Enum.GetValues(typeof(T)).Cast<T>();  
  11.   
  12.     Dictionary<string, T> enumMemberNameMappings = new Dictionary<string, T>();  
  13.   
  14.     foreach (T enumVal in enumVals)  
  15.     {  
  16.         string enumMember = enumVal.GetDescriptionFromEnumValue();  
  17.         enumMemberNameMappings.Add(enumMember, enumVal);  
  18.     }  
  19.   
  20.     if (enumMemberNameMappings.ContainsKey(enumMemberText))  
  21.     {  
  22.         retVal = enumMemberNameMappings[enumMemberText];  
  23.     }  
  24.     else  
  25.         throw new SerializationException($"Could not resolve value {enumMemberText} in enum {typeof(T).FullName}");  
  26.   
  27.     return retVal;  
  28. }  
The values expressed in the EnumMember attributes are loaded into a dictionary. The value of the attribute serves as the key and the associated enum is the value. The dictionary keys are compared to the string value passed to the parameter and if a matching EnumMember value is found, then the related enum is returned and so "AlexaSkillEvent.Enabled" returns RequestTypeEnum.SkillEnabled.
 
Using this method in a JSON Converter, the WriteJson method looks like the following,
  1. public class JsonEnumConverter<T> : JsonConverter where T : struct, Enum, IComparable, IConvertible, IFormattable 
  2. {  
  3.   
  4.     public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)  
  5.     {  
  6.         if (value != null)  
  7.         {  
  8.             Enum sourceEnum = value as Enum;  
  9.   
  10.             if (sourceEnum != null)    
  11.             {  

  12.                 string enumText = GetDescriptionFromEnumValue(sourceEnum);  
  13.                 writer.WriteValue(enumText);  
  14.             }  
  15.         }  
  16.     }  
Please note that an enum constraint is applied to the generic type class declaration. This wasn't possible until C# version 7.3. If you cannot upgrade to use C# version 7.3, just remove this constraint.
 
The corresponding ReadJson method is,
  1. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)  
  2. {  
  3.   
  4.     object val = reader.Value;  
  5.   
  6.     if (val != null)  
  7.     {  
  8.         var enumString = (string)reader.Value;  
  9.   
  10.         return GetEnumValue(enumString);  
  11.     }  
  12.   
  13.     return null;  
  14. }  
Now the class definition needs to apply the JsonConverter class to the RequestType property,
  1. [DataContract]  
  2. public class SamplePoco  
  3. {  
  4.     [DataMember]  
  5.     [JsonConverter(typeof(JsonEnumConverter<RequestTypeEnum>))]  
  6.     public RequestTypeEnum RequestType { getset; }  
  7.   
  8. }   
Finally, the SamplePoco class is serialized to JSON, 
  1. SamplePoco enumPoco = new SamplePoco();  
  2.   
  3. enumPoco.RequestType = RequestTypeEnum.SkillEnabled;  
  4.   
  5. string samplePocoText = JsonConvert.SerializeObject(enumPoco);  
This generates the following JSON,
  1. {  
  2.   "RequestType":"AlexaSkillEvent.SkillEnabled"  
  3. }  
And deserialing the JSON yields the RequestTypeEnum.SkillEnabled value on the sample class.
  1. string jsonText = "{\"RequestType\":\"AlexaSkillEvent.SkillEnabled\"}";  
  2.   
  3. SamplePoco sample = JsonConvert.DeserializeObject<SamplePoco>(jsonText);  

Summary 

The EnumMember attribute is used to drive serializing of non-standard enum values using both DataContract serialization and Newtonsoft JSON serialization. Attached sample code shows other examples and unit tests. The Whetstone.Alexa NuGet package makes use of this technique and is also available for reference on GitHub.