[英]WCF deserialization of Dictionary where Enum type is key
I would like to aks you for your help. 我想请你帮忙。 I have here problem with WCF deserialization of Dictionary where Enum type is used as a key.
我有这里的字典的WCF反序列化问题,其中枚举类型用作键。
I have two data objects: 我有两个数据对象:
[DataContract]
public enum MyEnum : int
{
[EnumMember]
Value1 = 0,
[EnumMember]
Value2 = 1
}
and 和
[DataContract]
[KnownType(typeof(MyEnum))]
public class ReturnData
{
[DataMember]
public IDictionary<Enum, string> codes;
}
In fact ReturnData
class contains more data members but they are not important for my example. 事实上,
ReturnData
类包含更多数据成员,但它们对我的示例并不重要。
These data objects are returned by method: 这些数据对象由方法返回:
[OperationContract]
public ReturnData Method1()
{
ReturnData data = new ReturnData();
data.codes = new Dictionary<Enum, string>();
data.codes.Add(MyEnum.Value1, "stringA");
return data;
}
When I call Method1 from client side then next exception is thrown: 当我从客户端调用Method1然后抛出下一个异常:
The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:Method1Result .
格式化程序在尝试反序列化消息时抛出异常:尝试反序列化参数http://tempuri.org/:Method1Result时出错。 The InnerException message was 'Error in line 1 position 522. Element ' http://schemas.microsoft.com/2003/10/Serialization/Arrays:Key ' contains data of the ' http://schemas.datacontract.org/2004/07/AMService:MyEnum ' data contract.
设置InnerException信息是“错误在第1个位置522元素” http://schemas.microsoft.com/2003/10/Serialization/Arrays:Key “包含的数据的” http://schemas.datacontract.org/2004 / 07 / AMService:MyEnum的数据合同。 The deserializer has no knowledge of any type that maps to this contract.
反序列化器不知道映射到此合同的任何类型。 Add the type corresponding to 'MyEnum' 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.'
将与“MyEnum”对应的类型添加到已知类型列表中 - 例如,通过使用KnownTypeAttribute属性或将其添加到传递给DataContractSerializer的已知类型列表中。
Any idea how to define ReturnData class to solve this problem? 知道如何定义ReturnData类来解决这个问题吗?
Note: When I change ReturnData
member codes
to use as key data type MyEnum
instead of Enum
public IDictionary<MyEnum, string> codes;
注意:当我更改
ReturnData
成员codes
以用作关键数据类型MyEnum
而不是Enum
public IDictionary<MyEnum, string> codes;
then deserialization works correctly and data are transferred from server side to client side without problem. 然后反序列化正常工作,数据从服务器端传输到客户端没有问题。
Thanks for your help. 谢谢你的帮助。
At the top of your class add a KnownType
attribute. 在您的类的顶部添加
KnownType
属性。
using System.Runtime.Serialization;
[KnownType(typeof(MyEnum))]
[DataContract]
public class Foo {
}
should'nt this line 不应该这样
data.codes = new Dictionary<Enum, string>();
be 是
data.codes = new Dictionary<MyEnum, string>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.