没有可序列化属性的二进制序列化

时间:2016-09-01 06:39:08

标签: c# .net serialization

我想要对我的对象进行搜索并使用BinaryFormatter类。

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

        formatter.Serialize(stream, message);

        return stream.ToArray();
    }
}

但是当我运行代码时,抛出一个异常。

  

SerializationException:Object未标记为可序列化。

我认为BinaryFormatter引发了这个异常。

我不想将[Serializable]标记为我的对象。或者我的图书馆用户可能忘记将[Serializable]标记为他们自己的消息。

有没有其他方法可以在不使用[Serializable]属性的情况下二进制序列化我的对象?

3 个答案:

答案 0 :(得分:2)

由于[Serializable]属性无法添加运行时,如果您想坚持使用内置的序列化.Net,则可以选择。

你可以

  1. 在IMessage中使用ISerializable接口,以便用户必须在其实现中实现序列化
  2. 使用第三方库,例如http://sharpserializer.codeplex.com/

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

答案 1 :(得分:1)

除了有关第三方库的其他答案之外,根据您的需要,您可以选择使用XmlSerializer。 (更好的是使用JSON serializer并不需要SerializeableAttribute。)

这些序列化程序不需要[Serializeable]。但是,XmlSerializer也不允许接口的序列化。如果你对混凝土类型很好,那就有效。 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;
    }
}

答案 2 :(得分:0)

为避免需要[Serializable]属性的内置序列化Net4x,请在Netcore 3.1+或Net5中使用Newtonsoft.Json或System.Text.Json

 
string json= JsonConvert.SerializeObject(message); 

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