序列化/反序列化对象 - 秩序领域的问题? [英] Serialize/deserialize objects - order of fields matters?
问题描述
难道的DataContractSerializer
错误地反序列化的对象,如果该字段不是在正确(知道是什么意思)命令?
Is it possible that DataContractSerializer
wrongly deserializes an object if the fields are not in the "correct" (whatever that means) order?
这是我尝试序列化的类/反序列化没有订单的属性放在字段/属性。然而,我的领域之一一直被反序列化空
,即使它有一个非空值(它实际上包含字符串列表)。
The classes that I try to serialize/deserialize do not have order-attributes placed on fields/properties. Yet one of my fields always gets deserialized as null
even though it has a non-null value (it actually contains a list of strings).
当我搬进序列化的文件中的两个XML元素周围,以匹配另一个XML例子的顺序(这没有问题反序列化工作)一切都开始工作。
When I moved two XML elements in serialized file around to match the order in another XML example (for which deserialization worked without problems) everything started to work.
这是没有意义的我,但也许有人知道更好。 ;)
This makes no sense to me but maybe someone knows better. ;)
推荐答案
为了符合正确的序列化/序列化的的DataContractSerializer
,以下所有条件都要满足。
To be eligible for correct serialization / serialization by the DataContractSerializer
, all of the following must be true.
- 必须被序列化必须有
SerializableAttribute
或DataContractAttribute
设置类; - 的属性和必须序列化类的字段需要的
DataMemberAttribute
集; - 的序列化属性或字段的数据类型必须是可序列化(即有一个公共构造函数和继承ISerializable的);
- 必须被序列化必须实现的类
IExtensibleDataObject
; - 注:序列化字段可以是公共或私有
- <一个href="http://theburningmonk.com/2010/08/wcf-be-ware-of-the-field-ordering-when-using-datacontractserializer/"相对=nofollow>会员必须按字母顺序排列或你应该使用<一个href="https://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.order.aspx"相对=nofollow>
订单
-property 中的DataMemberAttribute
。 李>
- The class that must be serialized must have
SerializableAttribute
orDataContractAttribute
set; - The properties and fields of the class that must be serialized require the
DataMemberAttribute
set; - The datatype of the serializable property or field must be serializable (i.e., have a public ctor and inherit ISerializable);
- The class that must be serialized must implement
IExtensibleDataObject
; - Note: serializable fields can be either public or private.
- Members must be in alphabetical order or you should use the
Order
-property of theDataMemberAttribute
.
因此,声明顺序的确实的事情。如果成员不是按字母顺序排列,它们被跳过。查找<一个href="http://stackoverflow.com/questions/2519240/wcf-datacontract-some-fields-do-not-deserialize">this在计算器回答为例,也许它适用于你的情况。
So, the order of the declaration does matter. If members are not in alphabetical order, they are skipped. Look up this answer at StackOverflow for an example, perhaps it applies to your case.
这篇关于序列化/反序列化对象 - 秩序领域的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!