【问题标题】:Serialize/Deserialze to a string C#序列化/反序列化为字符串 C#
【发布时间】:2012-05-10 15:49:35
【问题描述】:

第一次在 C# 中使用序列化...任何帮助将不胜感激! 以下是我的通用序列化器和反序列化器:

    public static string SerializeObject<T>(T objectToSerialize)
    {
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream memStr = new MemoryStream();

        try
        {
            bf.Serialize(memStr, objectToSerialize);
            memStr.Position = 0;

            return Convert.ToBase64String(memStr.ToArray());
        }
        finally
        {
            memStr.Close();
        }
    }

    public static T DeserializeObject<T>(string str)
    {
        BinaryFormatter bf = new BinaryFormatter();
        byte[] b = System.Text.Encoding.UTF8.GetBytes(str);
        MemoryStream ms = new MemoryStream(b);

        try
        {
            return (T)bf.Deserialize(ms);
        }
        finally
        {
            ms.Close();
        }
    }

这是我要序列化的对象:

[Serializable()]
class MatrixSerializable : ISerializable
{
    private bool markerFound;
    private Matrix matrix;

    public MatrixSerializable( Matrix m, bool b)
    {
        matrix = m;
        markerFound = b;
    }

    public MatrixSerializable(SerializationInfo info, StreamingContext ctxt)
    {
        markerFound = (bool)info.GetValue("markerFound", typeof(bool));

        matrix = Matrix.Identity;

        if (markerFound)
        {

            //deserialization code
        }
    }

    public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
    {
        // serialization code
    }

    public Matrix Matrix
    {
        get { return matrix; }
        set { matrix = value; }
    }

    public bool MarkerFound
    {
        get { return markerFound; }
        set { markerFound = value; }
    }
}

以及如何运行它的示例:

        MatrixSerializable ms = new MatrixSerializable(Matrix.Identity * 5, true);

        string s = Serializer.SerializeObject<MatrixSerializable>(ms);

        Console.WriteLine("serialized: " + s);

        ms = Serializer.DeserializeObject<MatrixSerializable>(s);

        Console.WriteLine("deserialized: " + ms.Matrix + " " + ms.MarkerFound);

当我尝试运行它时,我收到一个错误“SerializationException 未处理:输入流不是有效的二进制格式。起始内容(以字节为单位)是:41-41-45-41-41-41-44 -2F-2F-2F-2F-2F-41-51-41-41-41 ..."

任何关于我做错了什么或如何解决这个问题的建议将不胜感激!

【问题讨论】:

标签: c# c#-4.0 serialization deserialization


【解决方案1】:

您正在使用 Base64 将字节数组转换为字符串,并使用 GetUtf8 字节从字符串转换回字节数组。

System.Text.Encoding.UTF8.GetBytes(str); 替换为Convert.FromBase64String(str);

【讨论】:

  • 是的,当我看到你的帖子时才意识到我的错误......谢谢阿列克谢!
猜你喜欢
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-26
  • 2018-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多