Deserializing one contract type to another with DataContractSerializer
The model is fairly simple... two interfaces, two classes, 1 base.
public interface ISomeCar1, ICarBase
{
string x { get; set; }
string y { get; set; }
}
public class SomeCar1 : CarBase, ISomeCar1
{
public string x { get; set; }
public string y { get; set; }
}
public interface ISomeCar2, ICarBase
{
string x { get; set; }
string y { get; set; }
string z { get; set; }
}
public class SomeCar2 : CarBase, ISomeCar2
{
public string x { get; set; }
public string y { get; set; }
public string z { get; set; }
}
A third-party web service will return ArrayOfSomeCar1 or ArrayOfSomeCar2
depending upon the requested car type (1 or 2) passed into the service. In
reality, the third-party provider extended SomeCar1 to support z and
created SomeCar2. SomeCar1 is still there for backward compatibility. Long
story short, we have to pass in 1 or 2 depending on some local business
rules.
I would like to pass type 1 to the third-party web service, which will
respond with an XML root of ArrayOfSomeCar1, but I need to deserialize
this as SomeCar2 which supports all of the functionality of SomeCar1. The
extra feature in these cases would simply be ignored with business logic.
I've tried using KnownTypes, deriving one class from the other class,
adding the interface ISomeCar1 to the SomeCar2 class, deserializing to the
base class, etc... and nothing seems to work. I get back an error like
"ArrayOfSomeCar1 was unexpected" or "Expecting ArrayOfAnyType". I can
provide the specific errors if needed.
Our method calls to the service are 100% generic (i.e.
<TCollection<TEntity>, TEntity>) but I can't figure out which object needs
to derive from which interface/concrete class to make it deserialize as
Collection<SomeCar2> when I receive ArrayOfSomeCar1 as the root element.
We're using the DataContractSerializer and all of the classes are setup
properly to deserialize as the given type, but just not one type from
another type.
I have complete control over all the classes, brand-new project... Does
anyone have any suggestions/knowledge on how to make this work? I prefer
to use interfaces where ever possible.
No comments:
Post a Comment