views:

22

answers:

1

I need a very specific kind of .NET serializer.

My requirements:

  1. shouldn't skip private data
  2. output should be human-readable (or at least, easily parsable), preferably XML
  3. should support generic collections (no need to be easy, but it should be possible)
  4. should support custom-implemented serialization for specific classes.

I need (2) for my elaborate version-tolerance scheme and (4) because I need to implement custom optimized serialization for a huge object (array) that I need to serialize.

XmlSerializer fails (1).
BinaryFormatter fails (2).
SoapFormatter fails (3) and seems to be deprecated.
DataContractSerializer fails (4) AFAIK.
NetDataContractSerializer seems to fail (2) because I read it's not "interoperable" (though it does use XML??)
Protobuf-net fails (2).

Could you recommend a serializer to use?
Also: How is NetDataContractSerializer not interoperable? Please give me an example where it breaks interoperability.

Note: all of those serializers support version tolerance in one way or another, but I need more advanced version tolerance features. See this question of mine if you care about why.

Edit: It turns out that both DataContractSerializer and NetDataContractSerializer support both (2) and (4) so my question is solved.

A: 

I don't think you need a custom serializer, I think you need custom serialization methods in your classes.

For example: if you're using XmlSerializer, you can implement IXmlSerializable on your data class, and implement methods by hand that can cover any combination of versions, private or public data, or anything else. Similarly ISerializable can be used to customize behaviour if you're using binary serialization.

If you need to support generic collections, you could implement a class defined something like this to solve the problem (assuing the Xml serializer for sake of example):

public class FooList : List<Foo>, IXmlSerializable

This allows you to customize the serialization of a semi-generic collection class. Or, perhaps more reusable:

public class CustomSerializableList<T> : List<T>, IXmlSerializable where T : IXmlSerializable

... which gives you a generic list whose contents are guaranteed to be IXmlSerializable, which means the implementation of IXmlSerializable for the list itself is quite straightforward.

Dan Puzey
Yes, I *could* do all the serialization manually (all my serialized classes have important private data), but that would be a lot of unnecessary code that triplicates every field - once for the declaration, once for the serialization, and once for the deserialization. I hope to avoid that.
Stefan Monov