Serializing and deserializing a List<List<object>> with BinaryFormatter

Glimpse picture Glimpse · Sep 18, 2013 · Viewed 7.9k times · Source

Let's say I have

List<object> mainList = new List<object>();

And it contains

List<string> stringList = new List<string();
List<CustomClass> custList = new List<CustomClass>();
mainList.Add(stringList);
mainList.Add(custList);

To serialize

Stream stream;
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, mainList);

To deserialize

Stream stream = (Stream)o;
BinaryFormatter formatter = new BinaryFormatter();
List<object> retrievedList = (List<object>)formatter.Deserialize(stream);

At this point, I receive an error that the stream read (deserialization) reached the end of the stream without retrieving a value.

Do I need to specify something besides...

[Serializable]
public class CustomClass { .... }

in the custom class to make this work? Can I not deserialize a List> that contains different type of object every time?

I tried

IList list = (IList)Activator.CreateInstance(typeof(custClassList[0]))

and tried to send and receive this, but got the same issue.

I can however serialize and deserialize a specified type or List, but I really need it to be dynamic.

Answer

Glimpse picture Glimpse · Sep 24, 2013

Basically, BinaryFormatter is a joke. It works in some cases, but will fail in almost identical scenarios for unknown reasons.

The best and superior alternative to BinaryFormatter is the third-party library protobuf-net (https://github.com/mgravell/protobuf-net), developed by Marc Gravel.

This beauty solved all the problems I was having in one pass. It's much easier to set up and reacts more perfectly to complex, custom classes.

I should also mention that it's faster, in the terms of de/serialization.