WCF列表<string>序列化/反序列化错误

wd1*_*113 7 c# wcf serialization list deserialization

我有以下ServiceContract和DataContract类:

[ServiceContract] 
public interface IWcfService 
{ 
    [OperationContract] 
    Response GetData(); 
} 

[DataContract]
public class Response 
{ 
    [DataMember] 
    public Dictionary<string, object> Data { get; set; } 
} 
Run Code Online (Sandbox Code Playgroud)

当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.'.
Run Code Online (Sandbox Code Playgroud)

我还尝试将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; } 
} 
Run Code Online (Sandbox Code Playgroud)

但这一切都没有帮助.任何人对此都有任何想法?

更新

数据看起来像:

Data = new new DIctionary<string, object> 
       { 
           {"_id", 12344}, 
           {"names", new List<string>{ "John", "Peter", "Jack"}}, 
           {"time", DateTime.Now} 
       }
Run Code Online (Sandbox Code Playgroud)

我们之所以使用Dictionary <string,object>:Server需要向客户端发送'dynamic'数据的字典,可以是int,List,DataTime等.它将通过使用Dictionary帮助解决这个问题,但它也丢失了原始类型信息.例如,客户端需要List并执行一些数据绑定以显示集合,因此List.ToString()在这种情况下没有帮助.

wd1*_*113 1

感谢大家的意见。我通过将 WCF 配置为使用 NetDataContractSerializer 作为序列化器(默认序列化器是 DataContractSerializer)成功解决了该问题。NetDataContractSerializer 在进行序列化时将包含更多 CLR 类型信息,尽管它会影响性能(大约是序列化时间的两倍)。