What is the most flexible serialization for .NET objects, yet simple to implement?


I would like to serialize and deserialize objects without having to worry about the entire class graph.

Flexibility is key. I would like to be able to serialize any object passed to me without complete attributes needed throughout the entire object graph.

That means that Binary Serialization is not an option as it only works with the other .NET Platforms. I would also like something readable by a person, and thus decipherable by a management program and other interpreters.

I've found problems using the DataContract, JSON, and XML Serializers.

  • Most of these errors seem to center around Serialization of Lists/Dictionaries (i.e. XML Serializable Generic Dictionary).
  • "Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer."

Please base your answers on actual experiences and not theory or reading of an article.


I agree that the DataContract-based serialization methods (to JSON, XML, etc) is a bit more complex than I'd like.

If you're trying to get JSON check out http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

It's part of the MS AJAX extensions. Admittedly it is flagged as Obsolete in .NET 3.5 but ScottGu mentions in his blog comment here (http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx#4301973) that he's not sure why and it should be supported for a bit longer.

You should use the NetDataContractSerializer. It covers any kind of object graph and supports generics, lists, polymorphism (the KnownType attribute is not needed here), recursion and etc. The only drawback is that you have to mark all you classes with [Serializable] / [DataContract] attributes, but experience shows that you have to do some sort of manual fine-tuning anyway since not all members should be persisted. Also it serializes into an Xml, though its readability is questionable.

We had the same requirements as yours and chose this solution.

By : 171

For interoperability we have always used Xml Serialisation and made sure our class was designed from the ground up to do it correctly.

We create an XSD schema document and generate a set of classes from that using XSD.exe. This generates partial classes so we then create a set of corresponding partial classes to add the extra methods we want to help us populate the classes and use them in our application (as they are focused on serialising and deserialising and are a bit difficut to use sometimes).

By : Brody

This video can help you solving your question :)
By: admin