如何使用内部字典序列化对象数组

How to serialize object array with a dictionary inside

我正在尝试序列化一个包含字典作为其值之一的对象数组,我得到了这个 运行-time SerializationException:

Type 'System.Collections.Generic.Dictionary`2 ...with data contract name 'ArrayOfKeyValueOfstringanyType
is not expected. Consider using a DataContractResolver if you are using 
DataContractSerializer or add any types not known statically to the list of 
known types - for example, by using the KnownTypeAttribute attribute or by 
adding them to the list of known types passed to the serializer.

这就是我试图完成任务的方式:

        object[] taskArgs = new object[] { 1, 2 };
        IDictionary<string, object> kwargs = new Dictionary<string, object>();
        IDictionary<string, object> embed = new Dictionary<string, object>();
        embed.Add("callbacks", null);
        embed.Add("errbacks", null);
        embed.Add("chain", null);
        embed.Add("chord", null);


        var knownTypes = new List<Type> { typeof(IDictionary<string, object>), typeof(object []), typeof(List<string>) };
        //object[] arguments = new object[] { taskArgs, "{}", "{}"  };
        object[] arguments = new object[] { taskArgs, kwargs, embed };

        MemoryStream stream1 = new MemoryStream();
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(object[]), knownTypes);
        ser.WriteObject(stream1, arguments);
        stream1.Position = 0;
        StreamReader sr = new StreamReader(stream1);
        string message = sr.ReadToEnd();

尽管我尝试将 typeof(IDictionary<string, object>) 添加到 knownTypes,但它不会起作用。

对于已知类型,您必须使用具体类型 typeof(Dictionary<string, object>) 而不是接口类型 typeof(IDictionary<string, object>)

var knownTypes = new List<Type> { typeof(Dictionary<string, object>), typeof(object[]), typeof(List<string>) };

已知类型列表中的一个类型与要生效的其他未知类型的对象的确切类型(由 GetType() 返回)非常匹配。匹配基本 class 类型或实现的接口类型是不够的,无论如何数据协定序列化器不支持序列化接口。