Reputation: 3419
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!
Upvotes: 1
Views: 97
Reputation: 5515
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.
Upvotes: 0
Reputation: 1062865
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.
Upvotes: 1