gpt4 book ai didi

c# - WCF List 序列化/反序列化错误

转载 作者:太空狗 更新时间:2023-10-29 20:33:53 25 4
gpt4 key购买 nike

我有以下 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 类型时,客户端在接收到数据并尝试反序列化时抛出以下异常:

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 :服务器需要向客户端发送一个“动态”数据的字典,可以是int、List、DataTime等。使用Dictionary有助于解决这个问题,但也会丢失原始类型信息。例如,客户端需要 List 并进行一些数据绑定(bind)以显示集合,因此 List.ToString() 在这种情况下将无济于事。

最佳答案

我认为默认情况下 System.Object 不是 Serializable。您需要发送额外的信息,但这仍然不是最佳实践,我建议在使用您的字典之前定义一个单独的类型。

引用以下内容:

WCF service returning an array of dictionary

WCF System.Object Serialization

Serializing IDictionary in WCF

关于c# - WCF List<string> 序列化/反序列化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19491746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com