不能从string创建的流中反序列化对象

时间:2013-08-21 12:56:43

标签: c# serialization deserialization

我想创建将对象序列化为文件的方法。比我读取文件并将内容作为字符串。我将String保存在数据库中,而不是从DB中读取字符串,并将其反序列化为Object

我几乎做到了,但我收到错误there is no map for object

这是我序列化对象的方式

public static String Serialize(Object toSerialize)
    {
        Random random = new Random();
        int randomNumber = random.Next(100000, 1000000000);
        String fileName = randomNumber + ".txt";

        fileName = "EmployeeInfo.txt";

        Stream stream = File.Open(fileName, FileMode.Create);
        BinaryFormatter bformatter = new BinaryFormatter();

        bformatter.Serialize(stream, toSerialize);
        stream.Close();

        String fileContent = File.ReadAllText(fileName);

        return fileContent;
    }

这就是我将String转换为Stream以进行反序列化

的方法
String serialized = Serializer.Serialize(user);

        MemoryStream mStream = new MemoryStream();
        StreamWriter writer = new StreamWriter(mStream);
        writer.Write(serialized);
        writer.Flush();
        mStream.Position = 0;

现在反序列化

 public static Object Deserialize(Stream stream)
    {
        Object returnObject;
        BinaryFormatter bformatter = new BinaryFormatter();
        returnObject = (Object)bformatter.Deserialize(stream);
        stream.Close();

        return returnObject;
    }

我在哪里弄错了?我应该做些什么才能使它有效?

1 个答案:

答案 0 :(得分:0)

得到了答案。

首先感谢@ I4V的评论:

这是我的序列化方法

public static String Serialize(Object toSerialize)
    {
        Random random = new Random();
        int randomNumber = random.Next(100000, 1000000000);
        String fileName = randomNumber + ".txt";

        fileName = "EmployeeInfo.txt";

        MemoryStream stream = new MemoryStream();

        BinaryFormatter bformatter = new BinaryFormatter();
        bformatter.Serialize(stream, toSerialize);

        String fileContent = Convert.ToBase64String(stream.ToArray());
        stream.Close();

        return fileContent;
    }

现在方法反序列化可以从String

反序列化对象
 public static Object Deserialize(String stringObject)
    {
        Object returnObject;
        byte[] bytes = Convert.FromBase64String(stringObject);

        MemoryStream stream = new MemoryStream(bytes);

        BinaryFormatter bformatter = new BinaryFormatter();
        returnObject = bformatter.Deserialize(stream);

        return returnObject;
    }

那就是