Why am I using the KnownType attribute wrong?

本秂侑毒 提交于 2019-12-05 14:39:19
Alex

In your response data there is no way to infer a concrete type. The type to deserialize is not specified in the response.

From MSDN:

To preserve type identity, when serializing complex types to JSON a "type hint" can be added, and the deserializer recognizes the hint and acts appropriately. The "type hint" is a JSON key/value pair with the key name of "__type" (two underscores followed by the word "type"). The value is a JSON string of the form "DataContractName:DataContractNamespace" (anything up to the first colon is the name). Using the earlier example, "Circle" can be serialized as follows.

http://msdn.microsoft.com/en-us/library/bb412170.aspx

See the section related to polymorphism.

Have you tried putting the KnownType attribute on ResponseData instead of RequestResult?

In that code sample you need [KnownType(typeof(DetectionResult))] to be an attribute of ResponseData rather than RequestResult.

I don't know if that's sufficient to resolve your problem

From my experience working with the DataContractSerializer and the XmlSerializer, when an unexpected type is met during serialization process, those serializers throw an exception; they don't simply do the best they can. Maybe the DataContractJsonSerializer does not support KnownTypes at all.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!