Reputation: 126
[SOLVED] There was an error deserializing the object of type 'Message'. The data at the root level is invalid
I have the following code for 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);
}
}
This is the class I'm serializing
[DataContractAttribute]
public class Message
{
public string MessageType = string.Empty;
public string MessageData = string.Empty;
}
Here is how it is used
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;
}
I have tried several different things I have found on google from similar issues, but I cannot fix the issue. Is there something wrong with the way I'm serializing?
Upvotes: 0
Views: 1511
Reputation: 126
[SOLVED]
There were two issues. The first issue is [DataContractAttribute] need to be [Serializable]
[Serializable]
public class Message
{
public string MessageType = string.Empty;
public string MessageData = string.Empty;
}
Second is related to something not visible in the code above. The 'bytes' array was initialized to a size greater than the data received, causing the Deserializer to not work properly.
I just created a new data array with the appropriate size to pass to the 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;
}
Upvotes: 1