Reputation: 6296
Is there anyway to serialize a List of datacontracts? I have created a datacontract for the list, something like this:
[DataContract]
class ItemList<T>
{
public ItemList()
{
items=new List<T>();
}
[DataMember]
public List<T> items;
}
I have 3 clases Config, Config_V1, Config_V2 with the attribute [Name="Config"] what let me use versioning between the 3 versions of the Config class. So I would like to serialize and deserialize between ItemList of this Config clases. I have tried something like:
ItemList<ConfigData_V1> l = new ItemList<ConfigData_V1>();
l.items.Add(config);
WriteObject<ItemList<ConfigData_V1>>("serialization.bin", l);
ItemList<ConfigData_V2> l2;
l2=ReadObject<ItemList<ConfigData_V2>>("serialization.bin");
But I get an error when deserializing with the ReadObj that says that it is expecting a list of ConfigData_V2 but it found a List of ConfigData_V1. Wouldn't it just use the versioning of ConfigData clases to resolve this conflict?
Upvotes: 0
Views: 1097
Reputation: 2216
When you deserialize an object (List<Contract1>
) it adds metadata to specify that a-the data is part of a List and b - the containing object is Contract1
.
If you look at the actual XML that is written you will see this in the nodes.
As a result, when you attempt to do a read into List<Contract2>
you break the definition of the model because you told it the contained data was Contract1
but you trying to read Contract2
.
There is an attribute [KnownType(Type)]
which could potentially help you if you state that Contract2 is a known type of Contract1
though that really breaks the entire concept of contracts......
Upvotes: 2