空值的 WCF DataContract 反序列化问题

标签 wcf serialization datacontractserializer datacontract

假设我有类似的东西:

[DataContract(Namespace="http://bla.bla")]
public class MyClass {
    [DataMember] public long ResponseCode { get; set; }
    [DataMember] public long Fee { get; set; }
}

以下内容来自 channel :

<ns0:MyResult>
    <ns2:ResponseCode xmlns:ns2="http://bla.bla">101</ns2:ResponseCode>
    <ns2:Fee xmlns:ns2="http://bla.bla"></ns2:Fee>
</ns0:MyResult>

我收到错误:

----> System.Xml.XmlException:值“”无法解析为类型“Int64”。 ----> System.FormatException:输入字符串的格式不正确。

我不明白为什么。 DataContractIsRequired 参数的默认值为 false,因此我希望它能够无错误地反序列化,并使用该类型的默认值初始化缺失值(零)。我错过了什么?

最佳答案

来自 - 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.

而不是“给定数据成员值

所以你的 XML 应该不带 <ns2:Fee>使其工作的元素

<ns0:MyResult>
    <ns2:ResponseCode xmlns:ns2="http://bla.bla">101</ns2:ResponseCode>
</ns0:MyResult>

但是,我也在寻找解决您问题的方法。如何让我的 WCF 捕获此异常并自动为 int 或 date 类型设置其默认值。

另一个想法是如果我尝试遵循 - 使用 i:nil="true"-

<MyParentElement xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<MyElement i:nil="true"></MyElement>
</MyParentElement>

它应该能够设置自定义默认值。我不一定希望客户端缺少元素来指示传递的默认值。缺少元素也可能意味着客户端正在使用旧版本的数据合约。

关于空值的 WCF DataContract 反序列化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4449722/

相关文章:

c# - 如何将具有固定模式的值数组反序列化为强类型数据类?

c# - 有效地序列化锯齿状字节数组

.net - F# 将构造函数添加到记录?

.net - 指示不是 WCF 数据契约(Contract)一部分的标准方法?

c# - TCP 错误代码 10061 : No connection could be made because the target machine actively refused it

c# - WCF + 单例 + 文件传输 + 多线程

wcf - 服务引用的正确 url 是什么?

c# - 无法使用 https 端点创建 wcf web 服务

c++ - 在磁盘上/从磁盘存储/加载 C++ 对象

java - 我是否应该预期 Java 序列化最终会被放弃?