1

我试图返回一个数组,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;
    }

运行它会给出错误消息,但我认为我得到了正确的 knowntype?

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

2 回答 2

1

您只需将以下属性添加到您的数据合同类。

[DataMember]
public object UsedForKnownTypeSerializationObject;

所以现在生成的代理包含您在数据合同上设置的 Knowtypes。我有同样的问题,这是我想出的唯一解决方案。如果您的 DataContract 类没有 Object 类型的属性,则生成的代理不包含声明的 knowtypes

例如:

[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; }

}

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

于 2013-08-20T15:44:57.363 回答
0

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

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

因为“d”是测试方法中的字典对象数组,并且您将其作为值存储在结果中,所以需要将类型添加到已知类型中。

查看此链接的“集合和已知类型”部分了解更多详细信息:http: //msdn.microsoft.com/en-us/library/aa347850.aspx

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

于 2012-09-18T16:13:13.820 回答