【问题标题】:Serialize and Deserialize object graph using BinaryFormatter使用 BinaryFormatter 序列化和反序列化对象图
【发布时间】:2013-02-16 19:35:26
【问题描述】:

我正在尝试将我的对象图序列化为字符串,然后将其从字符串中反序列化。如果我这样做,对象序列化就好了

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。

非常感谢任何帮助。谢谢。

【问题讨论】:

    标签: c# serialization binaryformatter


    【解决方案1】:

    这里有一些代码可以做你想做的事情(我认为)——但我不得不问——你为什么要序列化成这样的字符串?

    如果类足够简单,可以序列化为字符串,请使用更容易处理的 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;
        }
    
    }
    

    HTH

    【讨论】:

    • +1 用于 Base64 编码(以 ASCII 字符串格式表示二进制数据)。
    • 我将其序列化为字符串,以便将其存储在数据库中。如果有更好的方法我愿意接受建议。
    • 您能否更新原始问题以包含 Search 类?当我不知道您要序列化什么时,很难给出建议。
    猜你喜欢
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 2012-08-12
    相关资源
    最近更新 更多