【问题标题】:WCF default serializer do not serialize Dictionary<string,object> with null valuesWCF 默认序列化程序不使用空值序列化 Dictionary<string,object>
【发布时间】:2015-02-20 17:14:27
【问题描述】:

我有通过 WCF 从服务器检索数据的应用程序(servicecontract 接口、dataContracts 等)

我有对象PackedObject:

public class PackedObject
 {
    [DataMember]
    private String _objTypeName;

    [DataMember]
    private Guid _id;

    [DataMember]
    private Dictionary<string, object> _fields = new Dictionary<string,object>();

    ...
 }

我将 DataRow 中的 _fields Dictionary 填写为(列名)-->(该列中的值)

DataRow 中的某些单元格可以为空。 字典中所有非空值的对象正确序列化和反序列化。但是,如果值为 null,则服务将停止序列化而不会出现任何错误。 它不会停止工作:我的应用程序仍在尝试重复请求服务,并且我看到有关此新服务请求的新日志信息。 似乎DataContractSerializer 不想用空值序列化字典值(字典中具有非空值的其他项正确序列化)

我应该怎么做才能解决这个问题?

【问题讨论】:

  • 不将空值填充到字典中不是更好吗?
  • 因为 DataRow 是从数据库中获取的,而 db 中的某些单元格可以为空。另外我想在这本字典中存储一行的所有列的记录,因为稍后我会尝试做类似Guid ParentId = (Guid)_fields["parentId"]??Guid.Empty()的事情。
  • 你能展示一下你是如何用代码填充字典的吗?
  • 对象不适合 DTO。您应该定义您期望从服务返回的类型。

标签: c# wcf serialization dictionary


【解决方案1】:

添加到 DataContract 类的 DataMember 属性。然后将 KnownType 属性用于对象的预期类型。在以下示例中,我在集合中使用 int 或 bool:

[DataContract]
    [KnownType(typeof(int[]))]
    [KnownType(typeof(bool[]))]
    public class CompositeType
    {
        [DataMember]
        public object UsedForKnownTypeSerializationObject;

    [DataMember]
    public string StringValue
    {
        get;
        set;
    }
    [DataMember]
    public Dictionary<string, object> Parameters
    {
        get;
        set;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 2010-12-03
    • 1970-01-01
    相关资源
    最近更新 更多