2013-02-16 4 views
4

객체 그래프를 문자열로 직렬화 한 다음 문자열에서 직렬화하려고합니다. 나는 예외이BinaryFormatter를 사용하여 객체 그래프 직렬화 및 비 직렬화

using (var memStream = new System.IO.MemoryStream()) 
{ 
    mf.Serialize(memStream, this); 
    memStream.Seek(0, 0); 

    Search s; 
    using (var memStrClone = new System.IO.MemoryStream()) 
    { 
      memStream.CopyTo(memStrClone); 
      memStrClone.Seek(0, 0); 
      s = mf.Deserialize(memStrClone) as Search; 
    } 
} 

위의 코드는하지만, 문자열로 직렬화이

Search s; 
string xml = ToString<Search>(this); 
s = FromString<Search>(xml); 

public static TType FromString<TType>(string input) 
{ 
    var byteArray = Encoding.ASCII.GetBytes(input); 
    using (var stream = new MemoryStream(byteArray)) 
    { 
      var bf = new BinaryFormatter(); 
      return (TType)bf.Deserialize(stream); 
    } 
} 

public static string ToString<TType>(TType data) 
{ 
    using (var ms = new MemoryStream()) 
    { 
      var bf = new BinaryFormatter(); 
      bf.Serialize(ms, data); 
      return Encoding.ASCII.GetString(ms.GetBuffer()); 
    } 
} 

같은 같은 문자열을 역 직렬화하려고 작품을 던졌습니다 할 경우 목적은 잘 직렬화

오브젝트 유형 '1936026741 Core.Sebring.BusinessObjects.Search.Search'에 대한 어셈블리 ID가 없습니다.

모든 도움을 주시면 감사하겠습니다. 감사.

답변

8

다음은 원하는대로 할 수있는 코드입니다 (하지만).하지만 물어볼 필요가 있습니다. 왜 그런 문자열로 직렬화할까요?

클래스가 문자열에 직렬화 할만큼 간단하면 처리하기가 훨씬 쉬운 XML 직렬 변환기를 사용하십시오. 그것을 디스크에 직렬화하려면 바이너리를 파일에 쓰고, 복잡한 경우에는 직렬화하여 전송하십시오 - protobuf-net과 같은 것을 사용하십시오.

문제의 핵심은 ASCII 인코딩을 사용하려고한다는 것입니다. Base64 인코딩을 사용하고 있습니다. 어쨌든

는 - 여기 (나는 당신의 검색 클래스에서 추측 했어요!) 간다

class Program 
{ 
    [Serializable] 
    public class Search 
    { 
     public Guid ID { get; private set; } 

     public Search() { } 

     public Search(Guid id) 
     { 
      ID = id; 
     } 

     public override string ToString() 
     { 
      return ID.ToString(); 
     } 
    } 

    static void Main(string[] args) 
    { 
     Search search = new Search(Guid.NewGuid()); 
     Console.WriteLine(search); 
     string serialized = SerializeTest.SerializeToString(search); 
     Search rehydrated = SerializeTest.DeSerializeFromString<Search>(serialized); 
     Console.WriteLine(rehydrated); 

     Console.ReadLine(); 
    } 
} 

public class SerializeTest 
{ 
    public static Encoding _Encoding = Encoding.Unicode; 

    public static string SerializeToString(object obj) 
    { 
     byte[] byteArray = BinarySerializeObject(obj); 
     return Convert.ToBase64String(byteArray); 
    } 

    public static T DeSerializeFromString<T>(string input) 
    { 
     byte[] byteArray = Convert.FromBase64String(input); 
     return BinaryDeserializeObject<T>(byteArray); 
    } 

    /// <summary> 
    /// Takes a byte array and deserializes it back to its type of <see cref="T"/> 
    /// </summary> 
    /// <typeparam name="T">The Type to deserialize to</typeparam> 
    /// <param name="serializedType">The object as a byte array</param> 
    /// <returns>The deserialized type</returns> 
    public static T BinaryDeserializeObject<T>(byte[] serializedType) 
    { 
     if (serializedType == null) 
      throw new ArgumentNullException("serializedType"); 

     if (serializedType.Length.Equals(0)) 
      throw new ArgumentException("serializedType"); 

     T deserializedObject; 

     using (MemoryStream memoryStream = new MemoryStream(serializedType)) 
     { 
      BinaryFormatter deserializer = new BinaryFormatter(); 
      deserializedObject = (T)deserializer.Deserialize(memoryStream); 
     } 

     return deserializedObject; 
    } 

    /// <summary> 
    /// Takes an object and serializes it into a byte array 
    /// </summary> 
    /// <param name="objectToSerialize">The object to serialize</param> 
    /// <returns>The object as a <see cref="byte"/> array</returns> 
    public static byte[] BinarySerializeObject(object objectToSerialize) 
    { 
     if (objectToSerialize == null) 
      throw new ArgumentNullException("objectToSerialize"); 

     byte[] serializedObject; 

     using (MemoryStream stream = new MemoryStream()) 
     { 
      BinaryFormatter formatter = new BinaryFormatter(); 
      formatter.Serialize(stream, objectToSerialize); 
      serializedObject = stream.ToArray(); 
     } 

     return serializedObject; 
    } 

} 

Base64 인코딩을위한 HTH

+1

+1 (ASCII 문자열 형식의 바이너리 데이터를 표현하기 위해). –

+0

문자열을 serialize하여 데이터베이스에 저장할 수 있습니다. 더 나은 방법이 있다면 제안에 대한 열어보십시오. – andrewramka

+0

검색 클래스를 포함하도록 원래 질문을 업데이트 할 수 있습니까? 당신이 무엇을 직렬화하려고하는지 모를 때 조언하기가 어렵습니다. – Jay

관련 문제