Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize to a dynamic type

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.

like image 210
tavier Avatar asked Oct 08 '13 11:10

tavier


People also ask

Can JSON be dynamic?

In simple terms, any valid JSON literal string is also a valid ObjectScript expression that evaluates to a dynamic entity.

How do I deserialize JSON to an object?

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.

How do I deserialize a string in C#?

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.


1 Answers

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));
like image 182
Marc Gravell Avatar answered Oct 20 '22 04:10

Marc Gravell