I am trying to de-serialize my XML to get an array of a type which is created dynamically (using codedom) and after that I am using reflection to load that assembly and loading the type which is created dynamically. When I try to de-serialize my XML (which has got a collection of objects of this dynamically generated type) I am not sure how do I provide the type to the serializer.
My code sample:
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, here the problem is that I don't know the "myDynamicType" while writing the code. It will be created and compiled at runtime.
Please help.
In simple terms, any valid JSON literal string is also a valid ObjectScript expression that evaluates to a dynamic entity.
NET objects (deserialize) A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.
The trick here is the Type.MakeArrayType()
method on an instance of Type
. The parameterless version produces the vector type, i.e. typeof(Foo).MakeArrayType()
=== typeof(Foo[])
. There are other overloads for multi-dimensional arrays etc.
XmlSerializer serializer = new XmlSerializer(type.MakeArrayType());
However: you will not be able to cast it at the end; you will need to use object[]
or similar (using array variance of reference-types):
EQs = (object[])(serializer.Deserialize(reader));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With