2011-09-13 6 views
1

C#을 사용하여 직렬화 & 직렬화를 수행하는 동안 문제가 발생합니다. 기본적으로 DataContractSerializer를 사용하여 개체를 serialize합니다. 이 올바르게 작동하지만 지금은 위의 역 직렬화하는 방법에 대한 도움이 필요직렬화 및 역 직렬화 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

나는 deserialization을 위해 다음과 같이 google과 코드를 시도했다. string toDeserialise = System.Web.HttpContext.Current.Session [ "ProjectSetup"]. ToString(); DataContractSerializer dcs = 새 DataContractSerializer (typeof (ProjectSetup)); MemoryStream ms = 새 MemoryStream (Encoding.UTF8.GetBytes (toDeserialise)); obj = (ProjectSetup) dcs.ReadObject (ms); – Anil

+0

및 가져 오기 오류 : 'System.Collections.Hashtable'형식의 가져 오기 전용 컬렉션이 null 값을 반환했습니다. 입력 스트림에는 인스턴스가 null 인 경우 추가 할 수없는 컬렉션 항목이 들어 있습니다. 개체의 생성자 나 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'형식의 가져 오기 전용 컬렉션이 null 값을 반환했습니다. 입력 스트림에는 인스턴스가 null 인 경우 추가 할 수없는 컬렉션 항목이 들어 있습니다. 개체의 생성자 나 getter에서 컬렉션을 초기화하는 것을 고려하십시오. – Anil

+0

@Anil이 답변을 추가했습니다. –

8

발렌틴의 대답은 비 직렬화하는 방법을 보여줍니다. 귀하의 코멘트를 다시

:

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입니다. 몇 가지 아이디어 :

먼저 개인 세트를 추가하십시오. 예를 들면 :

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

또는 :

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

그렇지 않으면, 당신은 전에 - 직렬화 콜백을 사용할 수있는 속성이 더 지능합니다

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