2011-09-13 49 views
1

我在做序列化時遇到問題&使用c#反序列化。基本上我使用DataContractSerializer來序列化一個對象。c#中的序列化和反序列化#

這裏是我的序列化代碼:

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; 

這是正常工作,但現在我需要如何反序列化上面的幫助。

+0

阿尼爾,如果我的代碼工作,你可以將其標記爲答案。如果它不提供一些額外的信息。 –

+0

我試過谷歌和這樣的反序列化的代碼:string toDeserialise = System.Web.HttpContext.Current.Session [「ProjectSetup」]。ToString(); DataContractSerializer dcs = new DataContractSerializer(typeof(ProjectSetup)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(toDeserialise)); obj =(ProjectSetup)dcs.ReadObject(ms); – Anil

+0

並且出現錯誤:「System.Collections.Hashtable」類型的只讀集合返回空值。輸入流包含收集項目,如果實例爲空,則不能添加。考慮在對象的構造函數或getter中初始化集合。 – Anil

回答

1

我在想以下可以工作嗎?

string toDeserialise = yourValue; 
using(StringReader sr = new StringReader(toDeserialize)) 
using(XmlTextReader xmlReader = new XmlTextReader(sr)) 
{ 
    return (ProjectSetup)serializer.ReadObject(xmlReader); 
} 
+0

我收到此錯誤:類型'System.Collections.Hashtable'的只讀集合返回空值。輸入流包含收集項目,如果實例爲空,則不能添加。考慮在對象的構造函數或getter中初始化集合。 – Anil

+0

@Anil增加了一個解決這個問題的答案 –

8

Valentin的答案告訴你如何反序列化。

回覆您的評論:

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.

(注意:HashTable通常是值得避免,太)

這是因爲DataContractSerializer不運行構造,所以如果你有:

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

或者:

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

then myData將始終爲null進行反序列化。一些想法:

首先,嘗試添加一個私人設置;例如:

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

否則,你可以使用之前,反序列化回調:

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

或者:使財產更加智能化:

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