05 February 2017

Enum deserialization with Reflection

While you work on middleware integration applications, it quite common that the application being interacted are having different message exchange formats. Popular message exchange formats are XML & JSON.

Assume you are integrating an application which exposes data in XML format and you need send that data to another application which expects data to be sent in JSON.

So with XML de serilization you build an object and the object needs to de serialized into JSON text.

Problem statement

If your XSD has enumeration values with spaces, then upon generating the proxies, your .NET enum values will have XmlEnumAttribute applied to them.

If you use popular JOSN Serializer Newtonsoft.Json, then you will not get the exact values as defined XmlEnumAttribute in a more readable fashion.

The JSON de serialization text for LoanType will have either integer value(0, 1, 2, 3). This might not be acceptable for the receiving system. Then you need write custom logic in getting the XmlEnumAttribute values for enum values.

Solution to the problem

We can use Reflection to solve the problem here to get the XmlEnumAttribute for enum values. Something like below in C# .NET.