如何正确设置DataContractSerializer()?

时间:2016-03-09 14:54:32

标签: c#

public string Serialize(BackgroundJobInfo info)
{
    var serializer = new DataContractSerializer(typeof(BackgroundJobInfo),
                     null, int.MaxValue, true, true, new MongoDbSurrogate());
    var stringBuilder = new StringBuilder();

    using (var stringWriter = new StringWriter(stringBuilder, CultureInfo.InvariantCulture))
    {
        var writer = XmlWriter.Create(stringWriter);
        serializer.WriteObject(writer, info);
        writer.Flush();
    }

    return stringBuilder.ToString();
}

这就是我创建serializer

的方式
var serializer = new DataContractSerializer(typeof(BackgroundJobInfo), null,
 int.MaxValue, true, true, new MongoDbSurrogate()); // MongoDbSurrogate: IDataContractSurrogate

之后我开始有以下例外:

System.Runtime.Serialization.SerializationException

类型的例外情况

Type System.Collections.ObjectModel.Collection 1[[Replay.Common.Contracts.Transfer.ExcludedWriter, Common.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] with data contract name ArrayOfExcludedWriter:http://schemas.datacontract.org/2004/07/Replay.Common.Contracts.Transfer' 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.

我已向[KnownType(typeof(some_type_in_exception))]添加了6 BackgroundJobInfo。我仍然得到不同类型的相同例外。

也许我做错了(例如构造函数中的第二个参数(已知类型)必须与null不同)?我该如何解决我的问题?

1 个答案:

答案 0 :(得分:0)

  

我已经向BackgroundJobInfo添加了6 [KnownType(typeof(some_type_in_exception))]。我仍然得到不同类型的相同例外。

您的解决方案正常运行。你还没找到全部。没有神奇的方法可以找到它们,你是程序员,你应该知道使用了什么类型。你将不得不继续找到它们。