ShouldSerialize pattern and DataContractSerializer

后端 未结 2 490
余生分开走
余生分开走 2020-12-10 19:31

Is there a way to get the ShouldSerialize* pattern working with DataContractSerializer?

Here is a small example:

I have a simple cl

相关标签:
2条回答
  • 2020-12-10 19:44

    You should set the IsRequired attribute on the DataMember:

    [DataContract]
    public class Person
    {
      [DataMember(IsRequired = False, EmitDefaultValue = False)]
      public string FirstName { get; set; }
      ...
    }
    
    0 讨论(0)
  • 2020-12-10 19:55

    AFAIK, ShouldSerialize* does not work with datacontract serializer. It is useless in the Kevin answer. You can remove it. Unfortunatly, the code given only work if you handle null value.

    Here is a more generic solution: It returns null value depending of a given condition.

        [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;
            }
          }
        }
    
    0 讨论(0)
提交回复
热议问题