Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

.net - WCF Disable Deserialization Order Sensitivity

I have a recurring problem when passing Serialized objects between non-.NET Clients, and .NET WCF Services.

When WCF Deserializes objects, it is strictly dependant upon the order of properties.

That is, if I define my class as:

public class Foo 
{ 
  public int ID { get; set; } 
  public int Bar { get; set; } 
} 

Then WCF Will serialize the object as as:

<Foo>
  <Bar>123</Bar>
  <ID>456</ID>
</Foo>

Note: The properties are serialized in alphabetical order.

If you attempt to Deserialize an object which has the positions of Bar and ID swapped, WCF will treat the incorrectly positioned elements as null.

Whilst I know I can use the DataMember attribute, and force a specific ordering, I want to reduce the number of times I have to debug issues where fields are 'mysteriously' null.

So, my question is: Can you tell the WCF Deserializer to ignore the order of fields, when deserializing objects.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can specify the serialization order by decorating the elements in your data contract:

[DataContract]
public class Foo 
{ 
  [DataMember(Order=1)]
  public int ID { get; set; } 

  [DataMember(Order=2)]
  public int Bar { get; set; } 
}

So you can make sure the serialization order is the same all the time. But there is no way to tell the deserializer to "forget" about the order - the point is: this is handled by means of an XML schema, and done using the <xs:sequence> element - and that does imply and require order. You cannot just turn that off, I'm afraid.

Based on that XML schema, your non-.NET clients should be able to verify whether or not their XML that they're about to send conforms to that schema - and if it doesn't because the Bar and ID element have been swapped, they shouldn't be sending that invalid XML.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...