serialization and Deserialization in c#

Question

I am facing a problem while doing serialization & deserialization using c#. Basically i am using DataContractSerializer to serialize an object.

Here is my serialization code:

 var serializer = new DataContractSerializer(typeof(ProjectSetup));
     string xmlString;
     using (var sw = new StringWriter())
         {
             using (var writer = new XmlTextWriter(sw))
                 {
                  writer.Formatting = Formatting.Indented;
                  serializer.WriteObject(writer, DALProjectSetup);
                  writer.Flush();
                  xmlString = sw.ToString();
                 }
          }                
      System.Web.HttpContext.Current.Session["ProjectSetup"] = xmlString;

This is working correctly but now I need help on how to deserialize the above.

Solution

Valentin's answer shows you how to deserialize.

Re your comment:

i am getting this error: The get-only collection of type 'System.Collections.Hashtable' returned a null value. The input stream contains collection items which cannot be added if the instance is null.

(note HashTable would generally be worth avoiding, too)

That is because DataContractSerializer does not run a constructor, so if you have:

private readonly HashTable myData = new HashTable();
[DataMember]
public HashTable MyData { get { return myData; } }

or:

private readonly HashTable myData;
[DataMember]
public HashTable MyData { get { return myData; } }
public MyType() {
    myData = new HashTable();
}

then myData will always be null for deserialization. A few ideas:

First, try adding a private set; for example:

[DataMember]
public HashTable MyData { get; private set; }
public MyType() {
    MyData = new HashTable();
}

Otherwise, you could use a before-deserialization callback:

[OnDeserializing]
void OnSerializing(StreamingContext ctx) {
    myData = new HashTable();
}
private HashTable myData = new HashTable();
[DataMember]
public HashTable MyData { get { return myData; } }

Or: make the property more intelligent:

private HashTable myData;
[DataMember]
public HashTable MyData { get { return myData ?? (myData = new HashTable()); } }