简体   繁体   English

更改名称空间后,DataContractSerializer无法反序列化

[英]DataContractSerializer cannot deserialize after namespace changed

I have 50 classes marked with DataContractAttribute . 我有50个标有DataContractAttribute类。

These classes form a huge hierarchical tree, which is serialized/deserialized using the DataContractSerializer to xml. 这些类形成一个巨大的分层树,使用DataContractSerializer对xml进行序列化/反序列化。

All of them specify a custom datacontract namespace [DataContract(Namespace="http://example.com")] , except for 3 classes, which I've missed. 所有这些都指定了一个自定义datacontract命名空间[DataContract(Namespace="http://example.com")] ,除了3个类,我错过了。

// Old class definitions 
[DataContract(IsReference=true)]  // <-- forgot ns
public class Type1{}
[DataContract(IsReference=true)] // <-- forgot ns
public class Type2{}
[DataContract(IsReference=true)] // <-- forgot ns
public class Type3{}
[DataContract(IsReference=true, Namespace="http://example.com")] // <-- 47 more like this
public class Type4{} 

I want these 3 classes to use the same datacontract namespace as the other 47 classes. 我希望这3个类使用与其他47个类相同的datacontract命名空间。

After the change, all my previously-saved xmls fails to load. 更改后,我以前保存的所有xmls都无法加载。

// Changed to:
[DataContract(IsReference=true, Namespace="http://example.com")] // <-- changed ns
public class Type1{} 
[DataContract(IsReference=true, Namespace="http://example.com")] // <-- changed ns
public class Type2{} 
[DataContract(IsReference=true, Namespace="http://example.com")] // <-- changed ns
public class Type3{} 
[DataContract(IsReference=true, Namespace="http://example.com")]
public class Type4{}

I tried this method: 我试过这个方法:

DataContractSerializer - change namespace and deserialize file bound to old namespace DataContractSerializer - 更改命名空间并反序列化绑定到旧命名空间的文件

But got a SerializationException saying Deserialized object with reference id 'i5' not found in stream. 但得到一个SerializationExceptionDeserialized object with reference id 'i5' not found in stream. SerializationException Deserialized object with reference id 'i5' not found in stream.

How can I deserialize xmls saved before and after the namespace change? 如何在命名空间更改之前之后反序列化保存的xmls?

I would personally change the data contract and then create a script that parses the previously saved xmls to add the namespace info. 我个人会更改数据协定,然后创建一个脚本来解析以前保存的xmls以添加命名空间信息。 Quick and simple. 快速而简单。

Something like loading xmls as string and then calling: 像加载xmls作为字符串,然后调用:

xmlstr=xmlstr.Replace("<Type1>", "<Type1 xmlns:Namespace=\"http://example.com\">");

Or maybe create two classes (one with the old namespace and one with the new) create a mapping method so that you can deserialize the old xmls based on the old namespace and serialize them after mapping with the new namespace. 或者可以创建两个类(一个具有旧命名空间,一个具有新命名空间)创建映射方法,以便您可以基于旧命名空间反序列化旧xmls,并在使用新命名空间映射后对其进行序列化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM