WCF Cast on Deserialize JSON
I have a WCF Web Service that accepts a JSON-Formatted request. I have a method on the web service that accepts a parameter of type Container that is defined as fol开发者_开发技巧lows
[DataContract, KnownType(typeof(Foo))]
public class Container
{
[DataMember]
public IList<IFoo> SomeMember { get; set;}
}
Where Foo is a concrete implementation of IFoo. The clients do not know anything about my namespaces and types. Yet, unless they include a DataContract "type hint" (i.e. "__type":"Foo#SomeNamespace"), they get a 400 error with a stack trace that says "Unable to cast object of type "System.Object" to "SomeNamespace.IFoo".
Is there anything I can do to convince the JSON Deserializer to treat the incoming JSON Array as an array or List of Foo instead of an array of object without having to reinvent any deserialization wheels?
AFAIK the DataContractJsonSerializer requires the __type
field in this situation in order to know which type to instantiate. You will have to write a custom binding and custom serialization if you don't want this behavior. But even in this case you will need some indication from the client that you want to work with the concrete type.
Or why not directly work with the concrete type:
[DataContract]
public class Container
{
[DataMember]
public Foo[] SomeMember { get; set; }
}
精彩评论