Prevent XmlSerializer from auto instantiating List's on Deserialize

落爺英雄遲暮 提交于 2019-12-24 02:38:06

问题


Assuming I have this sample class:

public class MyClass
{
    public List<int> ListTest { get; set; }
    public string StringTest { get; set; }
    public int IntTest { get; set; }
}

And this code:

string xmlStr = "<MyClass><StringTest>String</StringTest></MyClass>";
XElement xml = XElement.Parse(xmlStr);
XmlSerializer ser = new XmlSerializer(typeof(MyClass));
using (XmlReader reader = xml.CreateReader())
{
    var res = ser.Deserialize(reader);
}

After the Deserialize is completed the value of res is:
ListTest -> Empty List with Count = 0 (NOT null).
StringTest -> "String" as expected
IntTest -> 0 as expect (default value of an integer).

I'd like the serializer to act the same (default(List<T>) which is null) with List's and not instantiate them.

How can I accomplish something like that?
BTW, I must use the XmlSerializer.


回答1:


You can use backup-property to serialize/deserialize property as array:

public class MyClass
{
    [XmlIgnore]
    public List<int> ListTest { get; set; }
    [XmlElement("ListTest")]
    public int[] _listTest
    {
        get { return ListTest?.ToArray(); }
        set { ListTest = value == null ? null : new List<int>(value); }
    }
    ...
}




回答2:


Mark your property as nullable:

public class MyClass
{
    [XmlArray(IsNullable = true)]
    public List<int> ListTest { get; set; }
    public string StringTest { get; set; }
    public int IntTest { get; set; }
}


来源:https://stackoverflow.com/questions/31984191/prevent-xmlserializer-from-auto-instantiating-lists-on-deserialize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!