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

后端 未结 5 1114
星月不相逢
星月不相逢 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:35

    I know this topic is old. This is the solution I came with. A class which encapsulates the type, and has implicit casting to the type. When serializing, the member variable can be marked with IsNullable = false without getting compiler errors, and blocking it from being serialized when null.

    public class Optional where T : struct, IComparable
    {
        public Optional(T valueObject)
        {
            Value = valueObject;
        }
    
        public Optional()
        {
        }
    
        [XmlText]
        public T Value { get; set; }
    
        public static implicit operator T(Optional objectToCast)
        {
            return objectToCast.Value;
        }
    
        public static implicit operator Optional(T objectToCast)
        {
            return new Optional(objectToCast);
        }
    }
    

    Then use it in your class

    [Serializable]
    [XmlRoot(ElementName = "foo")]
    public class foo
    {
       [XmlElement(ElementName = "myInteger", isNullable = false)]
       Optional myInt;
    }
    

    You can do things like

            myFoo.myInt = 7;
            int j = 8 + myFoo.myInt;
    

    For all purposes it's an int. For serialization purposes, it can be null and blocked from being serialized.

提交回复
热议问题