views:

478

answers:

1

I am trying to save a custom object as a user setting in a VB.net app. This object consists of a List(Of Pair(Of String, Object)). Pair is a custom class which has two read/write properties (a String and an Object).

If I put simple types like int, string, datetime as the second value of my pair, the setting is saved without any problem. But if I try to put something more complex, like a list, there seems to be a problem during serialization and my setting is not saved.

String values in my pairs are serialized like this:

<value1>Priority_1</value1>

Object values are serialized with a special attribute:

<value2 xsi:type="xsd:int">2</value2>

Seems like values of type Object are serialized differently, to "remember" what is the real type of the object. Why can't it do the same for more complex types like List(Of T)?

Can you think of any simple workaround? Any tip about XML serialization that may help me is also welcome :-)

+1  A: 

It can do that for an int stored in the object because it knows how to serialize an int. it does not know how to serialize your complex type.

Unless you use the [XmlInclude] attribute to tell it which types might possibly appear in that object. From the example:

   [WebMethod()]
   [XmlInclude(typeof(Car)), XmlInclude(typeof(Bike))]
   public Vehicle Vehicle(string licenseNumber) {
      if (licenseNumber == "0") {
         Vehicle v = new Car();
         v.licenseNumber = licenseNumber;
         return v;
      }
      else if (licenseNumber == "1") {
          Vehicle v = new Bike();
          v.licenseNumber = licenseNumber;
          return v;
      }
      else {
         return null;
      }
   }

where

[XmlRoot("NewVehicle")] 
public abstract class Vehicle {
    public string licenseNumber;
    public DateTime make;
}

public class Car : Vehicle {
}

public class Bike : Vehicle {
}
John Saunders
I added XmlInclude attributes on my serialized class and it works now. Thanks a lot!!
Meta-Knight