Type handling for list of derived classes

Dec 1, 2010 at 2:20 PM

I would like to serialise / desrialise a list of objects that derive from a base class. So something like:

class BaseClass {...}

class DerivedA : BaseClass {...};

class DerivedB: BaseClass{...};

List<BaseClass> myList = new List<BaseClass>;
myList.Add(new DerivedA());
myList.Add(new DerivedB());
myList.Add(new DerivedB());

To deserialise this I believe I would need to use a converter? I don't suppose there is anything akin to the XmlSerializer's attributes that you could use like this:

[XmlArray(ElementName = "BaseClassList")]
[XmlArrayItem(typeof(DerivedA), ElementName = "DrvA")]
[XmlArrayItem(typeof(DerivedB), ElementName = "DrvB")]
public List<BaseClass> BaseClasses { get; set; }

Which could be used to produce / consume:

<BaseClassList><DrvA aSpecificProp="1"/><DrvB bSpecificProp="2"/><DrvB  bSpecificProp="3"/></BaseClassList>

So perhaps I could end up using JSON like this:

  "SomeOtherInfo": "blah",
  "BaseClassList": [
    {"$type": DrvA, "aSpecificProp"="1"},
    {"$type": DrvB, "bSpecificProp"="2"},
    {"$type": DrvB, "bSpecificProp"="3"}