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

后端 未结 5 1078
星月不相逢
星月不相逢 2021-01-14 15:15

I have a class which is used for Xml Serialization.

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

 [XmlAttribute(\"la         


        
5条回答
  •  滥情空心
    2021-01-14 15:42

    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;
            }
        }
    

提交回复
热议问题