I have a bunch of different DTO classes. They are being serialized into an XML string at one point and shot over to client-side of the web app. Now when the client shoots back an XML string, I need to deserialize it back to an instance of the DTO class that it represents. The problem is that I want to make it generic and possibly a function which takes in an xml string and spits out an object of a type. Something like a long these lines:
public sometype? Deserialize (string xml)
{
//some code here
return objectFromXml;
}
EDIT: Horrible example! I just contradicted myself!
I cannot do the following:
Person person = Deserialize(personXmlStringFromClient);
because I don’t know that personXmlStringFromClient is a representation of Person DTO object instance.
I don’t know what serialized object is given to me and that seems to be my problem here. I’ve been reading about reflection and other techniques which involve sticking the type into the xml so that deserializer knows what to do with it. I can’t seem to pull it all together into one working piece. Also, in pretty much most examples, the author knows what type there will be after deserialization. Any suggestion is welcome! If I need to do something special with the serialization process, please share that too.
You can use a generic:
If you don’t know which type it will be, I assume you have a fixed number of possible types, and you could try deserializing to each one until you don’t encounter an exception. Not great, but it would work.
Or, you could inspect the start of the xml for the outer object name and hopefully be able to determine the type from there. This would vary depending on what the xml looks like.
Edit: Per your edit, if the caller knows the type that they are passing, could they supply the fully qualified typename as a string as an additional parameter to the service?
If so, you could do this:
and change the Deserialize method to be like this:
However, this only gets you an
object… If all of the types in question implement a common interface, you could deserialize as above but change the return type to the interface (and cast to it in the return statement)