Wednesday, May 02, 2012

Xml Serialize Interface Typed Members

If you try to serialize a class that has a public member of an interface type to xml file using the regular .net XmlSerializer, you will get an error: “Cannot serialize member {m} of type {t} because it is an interface.” ({m} and {t} are placeholders). 
In this post I suggest a workaround to this issue.

Consider the following scenario:

You have an object model like this:

 1: public class Car
   2: {
   3:     public string Model { get; set; }
   4:     public int Year { get; set; }
   5:     public IEngine Engine { get; set; }
   6: }
   7:  
   8: public interface IEngine
   9: {
  10:     void Work();
  11: }
  12:  
  13: public class ElectricEngine : IEngine
  14: {
  15:     int batteryPrecentageLeft;
  16:     public int BatteryPrecentageLeft
  17:     {
  18:         get { return this.batteryPrecentageLeft; }
  19:         set { this.batteryPrecentageLeft = value; }
  20:     }
  21:  
  22:     void IEngine.Work() { }
  23: }

If you would try to serialize myCar using the regular XmlSerializer, you will get the error above.

There are many reasons why you shouldn’t want to serialize an interface typed member. I will not dive into this debate right now. I assume that you have considered this before, and are just looking for a workaround.

So first lets understand what we are trying to achieve. 
In the example above, I expect the serialized output of myCar to be something like this:

   2:   <Model>Ford Focus</Model>
   3:   <Year>2011</Year>
   4:   <Engine>
   5:     <ElectricEngine FullAssemblyQualifiedTypeName="Common.ElectricEngine, Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
   6:       <BatteryPrecentageLeft>70</BatteryPrecentageLeft>
   7:     </ElectricEngine>
   8:   </Engine>
   9: </Car>

Read more: itaysk
QR: Inline image 1

Posted via email from Jasper-Net