Excluding some properties during serialization without changing the original class

后端 未结 4 1150
走了就别回头了
走了就别回头了 2020-11-29 11:06

I\'m trying to serialize an object with several properties, but I don\'t want to include all properties in the serialization. Also, I would like to change the date format.

4条回答
  •  时光取名叫无心
    2020-11-29 11:51

    If you're using XmlSerializer, XmlAttributeOverrides is probably what you need.

    Update: I've been investigating the possibilities of customizing the date format, and, as far as I can see, no pretty solutions exist.

    One option, as has been mentioned by others, is to implement IXmlSerializable. This has the drawback that you're completely responsible for (de-)serializing the entire object(-graph).

    A second option, with also quite an extensive list of drawbacks, is to subclass the base class (you mentioned it as an alternative in your post). With quite some plumbing, conversions from and to the original object, and the use of XmlAttributeOverrides you could build something like this:

    public class Test
    {
        public int Prop { get; set; }
        public DateTime TheDate { get; set; }
    }
    
    public class SubTest : Test
    {
        private string _customizedDate;
        public string CustomizedDate 
        { 
            get { return TheDate.ToString("yyyyMMdd"); }
            set 
            { 
                _customizedDate = value;
                TheDate = DateTime.ParseExact(_customizedDate, "yyyyMMdd", null); 
            }
        }
    
        public Test Convert()
        {
            return new Test() { Prop = this.Prop };
        }
    }
    
    // Serialize 
    XmlAttributeOverrides overrides = new XmlAttributeOverrides();
    XmlAttributes attributes = new XmlAttributes();
    attributes.XmlIgnore = true;
    overrides.Add(typeof(Test), "TheDate", attributes);
    
    XmlSerializer xs = new XmlSerializer(typeof(SubTest), overrides);
    SubTest t = new SubTest() { Prop = 10, TheDate = DateTime.Now, CustomizedDate="20120221" };
    xs.Serialize(fs, t);
    
    // Deserialize
    XmlSerializer xs = new XmlSerializer(typeof(SubTest));
    SubTest t = (SubTest)xs.Deserialize(fs);
    Test test = t.Convert();
    

    It ain't pretty, but it will work.

    Note that you're actually (de-)serializing SubTest objects in this case. If the exact type is important, this is not going to be an option too.

提交回复
热议问题