反序列化时出现 C# DataContractSerializer 异常 'The data at the root level is invalid'

C# DataContractSerializer exception when Deserializing 'The data at the root level is invalid'

[已解决] 反序列化 'Message' 类型的对象时出错。根级别的数据无效

我有以下 Serializing/Deserializing

代码
    public static byte[] Serialize(object Object)
    {
        using (var memoryStream = new MemoryStream())
        {
            DataContractSerializer serializer = new DataContractSerializer(Object.GetType());
            serializer.WriteObject(memoryStream, Object);
            return memoryStream.ToArray();
        }
    }

    public static Type Deserialize<Type>(byte[] SerializedData)
    {
        using (var memoryStream = new MemoryStream(SerializedData))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(Type));
            return (Type)serializer.ReadObject(memoryStream);
        }
    }

这是我正在连载的class

[DataContractAttribute]
public class Message
{
    public string MessageType = string.Empty;
    public string MessageData = string.Empty;
}

使用方法如下



    void Send(string MessageType, string Data)
    {
        Message message = new Message();
        message.MessageType = MessageType;
        message.MessageData = Data;
        byte[] byteData = Serializer.Serialize(message); // SERIALIZE

        // Send the data
        stream.Write(byteData, 0, byteData.Length);
    }

    Message Receive()
    {
        stream.Read(bytes, 0, bytes.Length);
        Message message = Serializer.Deserialize(bytes); // DESERIALIZE
        return message;
    }

我已经尝试了在 google 上从类似问题中发现的几种不同方法,但我无法解决问题。我序列化的方式有问题吗?

[已解决]

有两个问题。第一个问题是 [DataContractAttribute] 需要 [Serializable]

[Serializable]
public class Message
{
    public string MessageType = string.Empty;
    public string MessageData = string.Empty;
}

第二个与上面代码中不可见的内容有关。 'bytes' 数组被初始化为大于接收到的数据的大小,导致 Deserializer 无法正常工作。

我刚刚创建了一个具有适当大小的新数据数组以传递给反序列化器

Message Receive()
{
    int messageLength = stream.Read(bytes, 0, bytes.Length);
    byte[] data = new byte[messageLength];
    Array.Copy(bytes, data, messageLength);

    Message message = Serializer.Deserialize(data); // DESERIALIZE
    return message;
}