Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore a nullable property from serialization if it is null or empty?

I have a class which is used for Xml Serialization.

Inside which I have a nullable property which is decorated with XmlAttribute:

 [XmlAttribute("lastUpdated")]
 public DateTime? LastUpdated { get; set; }

How to ignore the property from serialization if it is null or empty?

I've tried the below but it doesn't serialize when there is a value (always ignores):

  [XmlIgnore]
        public DateTime? LastUpdatedValue { get; set; }

        [XmlAttribute("lastUpdated")]
       public DateTime LastUpdated { get; set; }

        public bool ShouldSerializeLastUpdated()
        {
            return LastUpdatedValue.HasValue;
        }
like image 327
The Light Avatar asked Nov 28 '22 16:11

The Light


1 Answers

Nullable is not directly supported by XmlSerialization.

If you want use a nullable property you must use a non nullable property and add a boolean property with the same name of property with the suffix "Specified" which specifie when the property must be serializable.

An example with your case :

    private DateTime? _lastUpdated;

    [XmlAttribute("lastUpdated")]
    public DateTime LastUpdated {
        get {
            return (DateTime)_lastUpdated;
        }
        set
        {
            _lastUpdated = value;
        }
    }

    public bool LastUpdatedSpecified
    {
        get
        {
            return _lastUpdated.HasValue;
        }
    }
like image 160
binard Avatar answered Dec 06 '22 07:12

binard