Using Reflection to serialize DTO’s

Suppose that you have a DTO (data transfer object) that you want to convert into a parameter array to be saved to file or sent over the web. You could serialize it and convert it to XML or JSON. But maybe you want to send it in an HTTP POST or GET and you don’t want to know anything about the class itself. You could use Reflection to iterate through the properties and extract the property names and values and output them to a string.

For example, this code will convert a class into a string suitable for a REST API call:

var properties = prefs.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
 
           properties.ToList().ForEach(property =>
                                           {
                                               var hasDataMemberAttribute = property.GetCustomAttributes(typeof(DataMemberAttribute), false);
                                               if (hasDataMemberAttribute.Length == 1)
                                               {
                                                   string name = property.Name.ToLower();
                                                   string value = String.Empty;
 
                                                   object objValue = property.GetValue(prefs, null);
                                                   if (null != objValue)
                                                       value = objValue.ToString();
 
                                                   // Only serialize properties marked with the [DataMember] attribute:
                                                   var hasBrokerMapAttribute = property.GetCustomAttributes(typeof(DataMemberBrokerMapAttribute),
                                                                                                            false);
                                                   if (hasBrokerMapAttribute.Length == 1)
                                                   {
                                                       name = ((DataMemberBrokerMapAttribute)hasBrokerMapAttribute[0]).Key;
                                                   }
 
                                                   if (value.Length > 0)
                                                   {
                                                       filter.Append(String.Concat("/", name, "=", value));
                                                   }
                                               }
 
                                           });
 
           Debug.WriteLine("Search Filter:" + filter);
           return filter.ToString();

Leave a Reply