我有以下 ServiceContract 和 DataContract 类:
[ServiceContract]
public interface IWcfService
{
[OperationContract]
Response GetData();
}
[DataContract]
public class Response
{
[DataMember]
public Dictionary<string, object> Data { get; set; }
}
当 Response.Data 字典的值是 int、string、double 或任何其他“简单”原始类型时,WCF 可以成功地序列化对象。但是当 Response.Data 字典的值是 List<string> 类型时,客户端在接收到数据并尝试反序列化时抛出以下异常:
Message=The formatter threw an exception while trying to deserialize the message:
There was an error while trying to deserialize parameter http://tempuri.org/:GetDataResult.
The InnerException message was 'Error in line 1 position 990.
Element 'http://schemas.microsoft.com/2003/10/Serialization/Arrays:Value' contains data from a type
that maps to the name 'http://schemas.microsoft.com/2003/10/Serialization/Arrays:ArrayOfstring'.
The deserializer has no knowledge of any type that maps to this name.
Consider using a DataContractResolver or add the type corresponding to 'ArrayOfstring'
to the list of known types - for example, by using the KnownTypeAttribute attribute or
by adding it to the list of known types passed to DataContractSerializer.'.
我还尝试将 KnownType 属性添加到 ServiceContract 和 DataContract,如下所示:
[ServiceContract]
[ServiceKnownType(typeof(List<string>))]
[ServiceKnownType(typeof(Dictionary<string, string>))]
[ServiceKnownType(typeof(Dictionary<string, List<string>>))]
public interface IWcfService
{
[OperationContract]
[ServiceKnownType(typeof(List<string>))]
[ServiceKnownType(typeof(Dictionary<string, string>))]
[ServiceKnownType(typeof(Dictionary<string, List<string>>))]
Response GetData();
}
[DataContract]
[ServiceKnownType(typeof(List<string>))]
[ServiceKnownType(typeof(Dictionary<string, string>))]
[ServiceKnownType(typeof(Dictionary<string, List<string>>))]
[KnownType(typeof(List<string>))]
[KnownType(typeof(Dictionary<string, string>))]
[KnownType(typeof(Dictionary<string, List<string>>))]
public class Response
{
[DataMember]
public Dictionary<string, object> Data { get; set; }
}
但这些都没有帮助。有人对此有任何想法吗?
更新
数据看起来像:
Data = new new DIctionary<string, object>
{
{"_id", 12344},
{"names", new List<string>{ "John", "Peter", "Jack"}},
{"time", DateTime.Now}
}
我们使用 Dictionary<string, object> 的原因:服务器需要向客户端发送一个“动态”数据的字典,可以是 int、List、DataTime 等。使用 Dictionary 将有助于解决这个问题,但它也会丢失原始类型信息。例如,客户端需要 List 并做一些数据绑定来显示集合,所以 List.ToString() 在这种情况下将没有帮助。