二进制序列化和反序列化不(通过字符串)创建文件 [英] Binary serialization and deserialization without creating files (via strings)

查看:199
本文介绍了二进制序列化和反序列化不(通过字符串)创建文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个包含函数从字符串序列化/反序列化对象/类。这就是它看起来像现在:

I'm trying to create a class that will contain functions for serializing/deserializing objects to/from string. That's what it looks like now:

public class BinarySerialization
    {
        public static string SerializeObject(object o)
        {
            string result = "";

            if ((o.GetType().Attributes & TypeAttributes.Serializable) == TypeAttributes.Serializable)
            {
                BinaryFormatter f = new BinaryFormatter();
                using (MemoryStream str = new MemoryStream())
                {
                    f.Serialize(str, o);
                    str.Position = 0;

                    StreamReader reader = new StreamReader(str);
                    result = reader.ReadToEnd();
                }
            }

            return result;
        }

        public static object DeserializeObject(string str)
        {
            object result = null;

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str);
            using (MemoryStream stream = new MemoryStream(bytes))
            {
                BinaryFormatter bf = new BinaryFormatter();
                result = bf.Deserialize(stream);
            }

            return result;
        }
    }

SerializeObject方法效果很好,但DeserializeObject没有。我总是得到一个异常消息,前分析已完成流的结尾遭遇。什么可能是错在这里?

SerializeObject method works well, but DeserializeObject does not. I always get an exception with message "End of Stream encountered before parsing was completed". What may be wrong here?

推荐答案

序列化对象的BinaryFormatter的结果是一个字节流,而不是一个字符串。
你不能只把该字节字符,例如C或Python的。

The result of serializing an object with BinaryFormatter is an octet stream, not a string.
You can't just treat the bytes as characters like in C or Python.

恩code中的序列化对象使用Base64 来得到一个字符串来代替:

Encode the serialized object with Base64 to get a string instead:

public static string SerializeObject(object o)
{
    if (!o.GetType().IsSerializable)
    {
        return null;
    }

    using (MemoryStream stream = new MemoryStream())
    {
        new BinaryFormatter().Serialize(stream, o);
        return Convert.ToBase64String(stream.ToArray());
    }
}

public static object DeserializeObject(string str)
{
    byte[] bytes = Convert.FromBase64String(str);

    using (MemoryStream stream = new MemoryStream(bytes))
    {
        return new BinaryFormatter().Deserialize(stream);
    }
}

这篇关于二进制序列化和反序列化不(通过字符串)创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆