包含字典的wcf .net4字典

时间:2012-09-18 10:45:25

标签: wcf .net-4.0 dictionary known-types

我正在尝试返回一个dictionary <string, object>数组,其中对象可能包含一个基本类型,如int,bool等,或者它可能包含另一个dictionary<string, object>数组

虽然我可以很好地序列化,但如果字典中有字典,它就不会反序列化。

我收到以下错误:

Error in line 1 position 543. 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:ArrayOfArrayOfKeyValueOfstringanyType'. The deserializer has no knowledge of any type that maps to this name. Consider using a DataContractResolver or add the type corresponding to 'ArrayOfArrayOfKeyValueOfstringanyType' 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.

班级:

[DataContract(Namespace = "CISICPD")]
[KnownType(typeof(Dictionary<string,object>))]
public class TestResponse
{
    [DataMember]
    public Dictionary<string,object>[] Results;
}

功能:

public TestResponse test(string test1, string test2)
    {
        TestResponse r = new TestResponse();
        r.Results = new Dictionary<string, object>[1];
        r.Results[0] = new Dictionary<string, object>();
        r.Results[0].Add("field1", 26);
        Dictionary<string, object>[] d = new Dictionary<string, object>[1];
        d[0] = new Dictionary<string, object>();
        d[0].Add("inner", 28);
        r.Results[0].Add("dictionary", d);
        return r;
    }

运行此命令会显示错误消息,但我认为我有正确的知识类型?

CISICPD.CPDClient t = new CISICPD.CPDClient();
CISICPD.TestResponse response = t.test("dgdf", "dfsdfd");

2 个答案:

答案 0 :(得分:1)

您只需将以下属性添加到datacontract类。

[DataMember]
public object UsedForKnownTypeSerializationObject;

现在生成的代理包含您在datacontract上设置的Knowtypes。我有同样的问题,这是我提出的唯一解决方案。如果您没有在DataContract类的Object类型的属性,生成的代理不包含声明的知识类型

例如:

[DataContract]
[KnownType(typeof(List<String>))]
public class Foo
{
    [DataMember]
    public String FooName { get; set; }

    [DataMember]
    public IDictionary<String, Object> Inputs { get; set; }

    [DataMember]
    private Object UsedForKnownTypeSerializationObject{ get; set; }

}

它不是那么漂亮,因为你最终得到了一个没有任何功能实现的虚拟属性。但是,我再没有其他解决方案。

答案 1 :(得分:0)

将此添加到TestResponse上的已知类型:

[KnownType(typeof(Dictionary<string, object>[]))]

因为&#34; d&#34;是测试方法中的一个Dictionary对象数组,并且您将其作为值存储在Results中,需要将类型添加到已知类型中。

查看&#34;收藏和已知类型&#34;有关详细信息,请参阅此链接的一部分:http://msdn.microsoft.com/en-us/library/aa347850.aspx

基本上,您作为对象存储在Results中的任何类型都需要添加KnownType。