WCF DataContract deserialization issue with empty values
Say i have something like:
[DataContract(Namespace="http://bla.bla")]
public class MyClass {
[DataMember] public long ResponseCod开发者_开发百科e { get; set; }
[DataMember] public long Fee { get; set; }
}
and the following is coming from a channel:
<ns0:MyResult>
<ns2:ResponseCode xmlns:ns2="http://bla.bla">101</ns2:ResponseCode>
<ns2:Fee xmlns:ns2="http://bla.bla"></ns2:Fee>
</ns0:MyResult>
I'm getting the error:
----> System.Xml.XmlException : The value '' cannot be parsed as the type 'Int64'. ----> System.FormatException : Input string was not in a correct format.
I don't understand why. The default value of IsRequired
parameter of DataContract
is false
so i expect it to deserialize without errors and initialize the missing value with default values for the type (zero). What am i missing?
from - http://msdn.microsoft.com/en-us/library/aa347792.aspx
Interaction with IsRequired
As discussed in Data Contract Versioning, the DataMemberAttribute attribute has an IsRequired property (the default is false). The property indicates whether a given data member must be present in the serialized data when it is being deserialized. If IsRequired is set to true, (which indicates that a value must be present) and EmitDefaultValue is set to false (indicating that the value must not be present if it is set to its default value), default values for this data member cannot be serialized because the results would be contradictory. If such a data member is set to its default value (usually null or zero) and a serialization is attempted, a SerializationException is thrown.
and not 'given data member value'
so you should have your XML without <ns2:Fee>
element to make it work
<ns0:MyResult>
<ns2:ResponseCode xmlns:ns2="http://bla.bla">101</ns2:ResponseCode>
</ns0:MyResult>
However, I am also looking for solution to your problem. How can I make my WCF catch this exception and set its default value automatically for type int or dates.
Another idea is if i try following - using i:nil="true" -
<MyParentElement xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<MyElement i:nil="true"></MyElement>
</MyParentElement>
it should be able to set custom default value. I do not necessarily want a missing element from client to indicate default value passed. Missing element could also mean client is using older version of data contract.
精彩评论