1

I want to serialize a class with a lot of properties. Some of those properties are complex. There are some of the type Bitmap, Color and much more, and they do not get serialized at all.

The approach I am using is the following:

        XmlSerializer serializer = new XmlSerializer(typeof(MyObject));

        MemoryStream stream = new MemoryStream();

        serializer.Serialize(stream, obj);

        stream.Flush();
        stream.Seek(0, SeekOrigin.Begin);

        XmlDocument returnDoc = new XmlDocument();
        returnDoc.Load(stream);

How can I create "custom" approaches for those complex properties? Until now I created the XML-Documents myself and went trough every single property and converted it to text.

An other example where I need this is on references. This class has got some references to other classes. I don't want the whole subclass to be serialized, but only the name of it.

I am sure there are different approaches on how to accomplish this. What would be the best way to go?

I already tought of making extra properties and ignoring the others (XmlIgnore()), but that would be an overhead.

Thanks!

El Mac
  • 3,256
  • 7
  • 38
  • 58

2 Answers2

1

Your best bet is to stop trying to serialize your domain model, and create a DTO model that represents just what you want to store, in the way you want to store it (i.e. geared towards your chosen serializer).

If you want to store a bitmap, then you probably want a byte[] property. If you want to store the name of something - a string. Then just map between them. Simple, pain-free, and much easier than trying to fight a serializer into doing something that it doesn't want to do.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

For properties that are not serializable you need to implement the serialization yourself. You could serialize these objects to a byte array and then use Base64 encoding to place them to XML. Check out the following link: XmlSerializer , base64 encode a String member.

However, if you do not need to serialize into XML, you can use binary serialization which will work on all properties.

Community
  • 1
  • 1
Igor Ševo
  • 5,459
  • 3
  • 35
  • 80
  • That's how I do it now... I just have to make the serializer use Base64... He creates a new property just for this? – El Mac Jul 04 '14 at 09:32
  • No, binary serialization will not "work on all properties". All serializers have scenarios that they support, and scenarios that they don't. In other news: `BinaryFormatter` is horrendously brittle and shouldn't be wished upon enemies – Marc Gravell Jul 04 '14 at 09:50