How to deserialize a dynamic type

I am trying to de-serialize my XML to get an array of a type that is being created dynamically (using code), and after that I use reflection to load this assembly and loading a type that is created dynamically. When I try to de-serialize my XML (which has a collection of objects of this dynamically generated type), I am not sure how to provide the type to the serializer.

My sample code is:

Assembly assembly = Assembly.LoadFile("myDynamicassembly.dll"); Type type = assembly.GetType("myDynamicType"); string xmlstring = myXml.OuterXml.ToString(); byte[] buffer = ASCIIEncoding.UTF8.GetBytes(xmlstring); MemoryStream ms = new MemoryStream(buffer); XmlReader reader = new XmlTextReader(ms); myDynamicType[] EQs; XmlSerializer serializer = new XmlSerializer(typeof(myDynamicType[])); EQs = (myDynamicType[])(serializer.Deserialize(reader)); 

So, the problem here is that I don't know "myDynamicType" when writing code. It will be created and compiled at runtime.

Please, help.

+7
c # xml serialization
source share
2 answers

The trick here is the Type.MakeArrayType() method for the Type instance. A version without parameters creates a vector type, i.e. typeof(Foo).MakeArrayType() === typeof(Foo[]) . There are other overloads for multidimensional arrays, etc.

 XmlSerializer serializer = new XmlSerializer(type.MakeArrayType()); 

However: you cannot throw it at the end; you will need to use object[] or similar (using the variance of an array of reference types):

 EQs = (object[])(serializer.Deserialize(reader)); 
+9
source share

I do not know that what I'm going to say is what you want, but:

You cannot deserialize it as an object type

 object[] EQs; XmlSerializer serializer = new XmlSerializer(typeof(object[])); EQs = (object[])(serializer.Deserialize(reader)); 

If the type of an object is determined at compile time (as you say), shouldn't there be some code that defines it? and in this code snippet do you just convert the object to the type you need?

Another way to convert once you have object[] EQs is this:

  if(EQs.Lenght > 0) { Type t = EQs[0].GetType(); } 

and now use the resulting Type to convert your object[] EQs to the right Type

0
source share

All Articles