ShouldSerialize模式和DataContractSerializer

时间:2012-07-09 12:00:19

标签: c# datacontractserializer

有没有办法让ShouldSerialize*模式与DataContractSerializer一起使用?

这是一个小例子:

我有一个简单的类Person,如下所示:

[DataContract]
public class Person
{
  [DataMember]
  public string FirstName { get; set; }
  public bool ShouldSerializeFirstName()
  {
    return !string.IsNullOrEmpty(FirstName);
  }

  [DataMember]
  public string LastName { get; set; }
  public bool ShouldSerializeLastName()
  {
    return !string.IsNullOrEmpty(LastName);
  }

  public Person(string firstName, string lastName)
  {
    FirstName = firstName;
    LastName = lastName;
  }
  public Person(string firstName)
  {
    FirstName = firstName;
  }
  public Person()
  {
  }
}

FirstNameLastName只应序列化,如果它们不为null或为空。这适用于XmlSerializer,但DataContractSerializer似乎忽略了ShouldSerialize模式。 *Specified模式也不起作用。

我正在创建两个不同的Xml文件。一个是DataContractSerializer,一个是XmlSerializer:

List<Person> persons = new List<Person>();
persons.Add (new Person("John", "Doe"));
persons.Add (new Person("Carl"));

DataContractSerializer serializer = new DataContractSerializer (typeof (List<Person>));
using (XmlWriter writer = XmlWriter.Create(@"c:\test1.xml", settings))
{
  serializer.WriteObject (writer, persons);
}

XmlSerializer xmlSerializer = new XmlSerializer (typeof (List<Person>));
XmlWriter xmlWriter = XmlWriter.Create (@"c:\text2.xml", settings);
xmlSerializer.Serialize (xmlWriter, persons);
xmlWriter.Close();

文件test1.xml(DataContractSerializer)的输出如下所示:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfPerson xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/XmlSerialization">
  <Person>
    <FirstName>John</FirstName>
    <LastName>Doe</LastName>
  </Person>
  <Person>
    <FirstName>Carl</FirstName>
    <LastName i:nil="true" />
  </Person>
</ArrayOfPerson>

文件test2.xml(XmlSerializer)的输出如下所示:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Person>
    <FirstName>John</FirstName>
    <LastName>Doe</LastName>
  </Person>
  <Person>
    <FirstName>Carl</FirstName>
  </Person>
</ArrayOfPerson>

2 个答案:

答案 0 :(得分:5)

AFAIK,ShouldSerialize *不适用于datacontract序列化程序。凯文的答案毫无用处。你可以删除它。 不幸的是,只有处理空值才能使代码有效。

这是一个更通用的解决方案:它根据给定条件返回空值。

    [DataContract]
    public class Person
    {
      private string firstName;
      [DataMember(IsRequired = false, EmitDefaultValue = false)]
      public string FirstName
      {
        get
        {
            //Put here any condition for serializing
            return string.IsNullOrWhiteSpace(firstName) ? null : firstName;
        }
        set
        {
            firstName = value;
        }
      }
    }

答案 1 :(得分:4)

您应该在DataMember上设置IsRequired属性:

[DataContract]
public class Person
{
  [DataMember(IsRequired = False, EmitDefaultValue = False)]
  public string FirstName { get; set; }
  ...
}