.NET: How to binary serialize an object with the [DataContract] attribute?

A class marked as [DataContract] cannot be ISerializable at the same time. OK, so how can I serialize this type of object to a binary stream?

private byte[] GetRoomAsBinary(Room room) { MemoryStream stream = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(stream, room); return stream.ToArray(); } 

I can not get it to work without putting ISerializable. How can I get an array of bytes from an object in a different way?

+6
wcf
source share
3 answers

The solution is to use a DataContractSerializer to serialize the object.

+3
source share

Code for serializing and deserializing using binary formatting:

 public static class BinarySerializer { public static byte[] Serialize<T>(T obj) { var serializer = new DataContractSerializer(typeof(T)); var stream = new MemoryStream(); using (var writer = XmlDictionaryWriter.CreateBinaryWriter(stream)) { serializer.WriteObject(writer, obj); } return stream.ToArray(); } public static T Deserialize<T>(byte[] data) { var serializer = new DataContractSerializer(typeof(T)); using (var stream = new MemoryStream(data)) using (var reader = XmlDictionaryReader.CreateBinaryReader( stream, XmlDictionaryReaderQuotas.Max)) { return (T)serializer.ReadObject(reader); } } } 

Application:

 public void TestBinarySerialization() { // Create the person object. Person person = new Person { Name = "John", Age = 32 }; // Serialize and deserialize the person object. byte[] data = BinarySerializer.Serialize<Person>(person); Person newPerson = BinarySerializer.Deserialize<Person>(data); // Assert the properties in the new person object. Debug.Assert(newPerson.Age == 32); Debug.Assert(newPerson.Name == "John"); } 
+25
source share

What is the principle of binary serialization: only [Serializable] classes can be serialized (although I may have read that this restriction was recently removed). If you want to take control of the serialization process, do ISerializable.

If the Room class has non-serializable elements, you will also need ISerializable.

What are room members?

0
source share

All Articles