Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize classes that were not designed to be serialized?

I need to save some classes and data structures to a file. My first reflex was to use XML or Binary serialization but this is turning into a nightmare. I have a set of classes that were not meant to be serialize (private setters, no parameterless constructors, no Serialization attribute, dictionaries, etc.). Considering that I cannot change those classes, what should I do? Is there any workaround this and still use serialization?

Am I going to have to write all the code to write the properties, collections, etc?

like image 871
Martin Avatar asked May 07 '09 00:05

Martin


1 Answers

Use the JavaScriptSerializer. It's in the System.Web.Script.Serialization namespace and is implemented in the 3.5 framework in the System.Web.Extensions.dll assembly.

With this class, you can serialize any POCO whether it's marked as [Serializable] or not. Your program does not have to be a web application to use JSON serialization. Here's an example:

public class Unserializable
{
  public int Age { get; set; }
  public int ID { get; set; }
  public string Name { get; set; }
}

public class Program
{
  static void Main()
  {
    var u = new Unserializable
            {
              Age = 40,
              ID = 2,
              Name = "Betty"
            };
    var jser = new JavaScriptSerializer();
    var jsonText = jser.Serialize( u );
    // next line outputs {"Age":40,"ID":2,"Name":"Betty"}
    Console.WriteLine( jsonText );
  }
}
like image 84
W. Kevin Hazzard Avatar answered Sep 28 '22 08:09

W. Kevin Hazzard