简体   繁体   English

WCF在反序列化JSON上投射

[英]WCF Cast on Deserialize JSON

I have a WCF Web Service that accepts a JSON-Formatted request. 我有一个WCF Web服务,它接受JSON格式的请求。 I have a method on the web service that accepts a parameter of type Container that is defined as follows 我在Web服务上有一个方法可以接受类型为Container的参数,其定义如下

[DataContract, KnownType(typeof(Foo))]
public class Container
{
    [DataMember]
    public IList<IFoo> SomeMember { get; set;}
}

Where Foo is a concrete implementation of IFoo. Foo是IFoo的具体实现。 The clients do not know anything about my namespaces and types. 客户端对我的名称空间和类型一无所知。 Yet, unless they include a DataContract "type hint" (ie "__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". 但是,除非它们包含DataContract“类型提示”(即“ __type”:“ Foo#SomeNamespace”),否则它们会显示400错误,且堆栈跟踪显示“无法将类型为“ System.Object”的对象转换为“ 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? 有什么我可以说服JSON Deserializer将传入的JSON数组视为Foo数组或Foo列表而不是对象数组的方法,而无需重新发明任何反序列化方法?

AFAIK the DataContractJsonSerializer requires the __type field in this situation in order to know which type to instantiate. AFAIK在这种情况下, DataContractJsonSerializer需要__type字段才能知道要实例化哪种类型。 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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM