ShouldSerialize pattern and DataContractSerializer

后端 未结 2 491
余生分开走
余生分开走 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: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;
            }
          }
        }
    

提交回复
热议问题