Question

I have a class with the following structure

    public class MyClass:
{
    public GMapMarker marker; // from GMap.NET library
    public TwitterStatus tweet; // from TweetSharp library
    public List<MYTriple> triples = new List<MYTriple>();
    public List<MYGraph> Graph = new List<MYGraph>();
}

and I have the list

List<MyClass> mylist;

I just want to serialize/save the list into a file and load it again in the next start of my program,

the list might contains hundreds of results, I only care about the performance.

I tried Jason, I got an Exception when Deserializing the list

InvalidOperationException Instances of abstract classes cannot be created

Was it helpful?

Solution

Different serialization options have different features and trade-offs. There is no one option that does everything you want, because:

  • not everything is [Serializable] (for BinaryFormatter) - plus BinaryFormatter is virtually always a bad choice
  • not everything has a public parameterless constructor suitable for XmlSerializer
  • and so on, for every serializer you can name (and trust me, I can name plenty): they all have different features and things they can/can't do - usually with good protocol reasons, not just apathy / incompetence

IMO, the problem here is that you are trying to serialize implementation details rather than serializing data. If you create a custom DTO model that just represents the data (but which has no dependency on 3rd-party types) then it will be possible to create a sane serialization model that works very efficiently with your choice of serializer, and which doesn't break horribly when you upgrade a library reference, or switch to a different library completely.

Some serializers (protobuf-net does, certainly) allow you to mix and match by way of serialization surrogate types, meaning you can tell it to silently substitute some types when it encounters them (in particular, if 80% of your model is serialization-friendly, this lets you swap out the other 20% as part of the engine) - but without knowing more about the specifics here it is hard to say whether that will help.

OTHER TIPS

You can use Json.net it most reliable using the code below

string json = JsonConvert.SerializeObject(mylist, Formatting.Indented);
File.WriteAllText(@"c:\mylist.json", json);

using json.net;

   File.WriteAllText(@".\temp.txt", JsonConvert.SerializeObject(myInstance));



  MyClass instanceOnLoad = JsonConvert.DeserializeObject<MyClass>(File.ReadAllText(@".\temp.txt"));

Doesn't get much easier than that!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top