Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary serialization without serializable attribute

I want to serailize my object and used BinaryFormatter class.

public static byte[] BinarySerialize(IMessage message)
{
    using (var stream = new MemoryStream())
    {
        var formatter = new BinaryFormatter();

        formatter.Serialize(stream, message);

        return stream.ToArray();
    }
}

But when I run the code, throws an exception.

SerializationException: Object is not marked as serializable.

I think this exception thrown by BinaryFormatter.

I do not want to mark as [Serializable] my objects. Or my library users may forget mark as [Serializable] their own Messages.

Is there any other way to binary serialize my objects without using [Serializable] attribute?

like image 570
barteloma Avatar asked Sep 01 '16 06:09

barteloma


People also ask

Is serializable attribute necessary?

Synopsis. This attribute is used in the class definition to indicate that a class can be serialized. By default, all fields in the class are serialized except for the fields that are marked with a NonSerializedAttribute . It is not necessary to use this attribute if a given type implements the System.

How do you avoid variables to serialize?

You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable. If the object must be serialized, apply the NonSerialized attribute to specific fields that store sensitive data.

What is the difference between binary serialization and XML serialization?

Xml Serializer serializes only public member of object but Binary Serializer serializes all member whether public or private. In Xml Serialization, some of object state is only saved but in Binary Serialization, entire object state is saved.

What is the purpose of serializable attribute?

Uses for Serialization. Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange.


2 Answers

Since [Serializable] attribute cannot be added runtime, there are nooptions if you want to stick to the .Net built in Serialization.

You can

  1. Use ISerializable interface in IMessage so that users has to implement Serialization in their implementations
  2. Use an external library such as: http://sharpserializer.codeplex.com/ And by the way, they have moved to GitHub. See: https://github.com/polenter/SharpSerializer

    public static byte[] BinarySerialize(IMessage message)
    {
        using (var stream = new MemoryStream())
        {
            var serializer = new SharpSerializer(true);
    
            serializer.Serialize(message, stream );
    
            return stream.ToArray();
        }
    }   
    
  3. Use JSON serialization

like image 117
Low Flying Pelican Avatar answered Oct 02 '22 12:10

Low Flying Pelican


In addition to the other answers regarding 3rd party libs, depending on your needs you may choose to use XmlSerializer. (Better yet use a JSON serializer that doesn't require the SerializeableAttribute.)

These serializers do not require [Serializeable]. However, the XmlSerializer doesn't allow serialization of interfaces either. If you are good with concrete types it works. Compare serialization options.

E.G.

void Main()
{
    var serialized = Test.BinarySerialize(new SomeImpl(11,"Hello Wurld"));
}

public class Test
{
    public static string BinarySerialize(SomeImpl message)
    {
        using (var stream = new StringWriter())
        {
            var formatter = new XmlSerializer(typeof(SomeImpl));

            formatter.Serialize(stream, message);

            return stream.ToString().Dump();
        }
    }

}

public class SomeImpl
{
    public int MyProperty { get;set;}
    public string MyString { get;set; }

    public SomeImpl() {}

    public SomeImpl(int myProperty, String myString)
    {
        MyProperty = myProperty;
        MyString = myString;
    }
}
like image 40
P.Brian.Mackey Avatar answered Oct 02 '22 14:10

P.Brian.Mackey