Is there a way to avoid the XmlSerializer to not initialize a null property when deserializing?

后端 未结 4 1742
旧巷少年郎
旧巷少年郎 2020-12-16 18:00

I have this class:

public class MySerializableClass
{
    public List MyList { get; set; }
}

If MyList is null when MySeria

相关标签:
4条回答
  • 2020-12-16 18:31

    If you add a property with the name *PropertyName*Specified as a boolean the XmlSerializer will render the tag for the list only when it is true.

    Example:

    public class MySerializableClass
    {
        public List<MyObject> MyList { get; set; }
    
        [XmlIgnore]
        public bool MyListSpecified { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-16 18:37

    Don't use Auto-Implemented Properties if you need a null there. use e.g.

    public class MySerializableClass 
    { 
        List<MyObject> myList 
        public List<MyObject> MyList { get {return myList;} set {myList = value;} } 
    } 
    
    0 讨论(0)
  • 2020-12-16 18:45

    I had the same problem but adding the XmlArrayAttribute to the property with nothing set made it work for me

    public class MySerializableClass
    {
        [XmlArray]
        public List<MyObject> MyList { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-16 18:51

    This looks like a bug...

    Even if you try to mark the property as nullable, it doesn't seem to work.

    [XmlArray(IsNullable = true)]
    public List<MyObject> MyList { get; set; }
    

    It serializes the MyList property as follows :

    <MyList xsi:nil="true" />
    

    So the XML clearly indicates that the list is null, but after deserialization, it is still initialized to an empty list...

    If you replace List<MyObject> with MyObject[], it works fine (even without IsNullable = true), but it's probably not what you want...

    You should probably report this on Connect.

    0 讨论(0)
提交回复
热议问题