9

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?

7
  • Check Protobuf, that shall not need Serializable attribute Commented Sep 1, 2016 at 6:43
  • var result = BinarySerialize(JsonConvert.SerializeObject(message)); Commented Sep 1, 2016 at 6:51
  • 1
    var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)); Commented Sep 1, 2016 at 6:51
  • go through two stages of serialization? Commented Sep 1, 2016 at 6:51
  • How to deserialize? Binary deserialization returns original object that namespace and class info. But Json deserialization returns only object like this {"id": "000"} Commented Sep 1, 2016 at 11:18

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Json will be text serialization, OP needs binary serialization, may not fit in
Yeah.. then easiest would be to use sharpserializer, with minimal changes to his code
2

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;
    }
}

Comments

1

To avoid Net4x built in Serialization that require the [Serializable] attribute, use Newtonsoft.Json or System.Text.Json in netcore 3.1+ or Net5

 
string json= JsonConvert.SerializeObject(message); 

//or System.Text.Json in netcore 3.1+
string json=  System.Text.Json. JsonSerializer.Serialize(message);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.