Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I deserialize an interface type?

I serialize a class which includes a property called Model as IModel but when I try to Deserialize it I'm getting the following exception:

System.Runtime.Serialization.SerializationException: Type 'MYN.IModel' in Assembly 'MYN.Defs, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

It's binary serialization. Model marked as serializable. Obviously IModel is not.

So what's the solution, what am I doing wrong? Why does it try to seriliaze or deserialize an interface anyway?

P.S. Interface hasn't got an Enum in it.

like image 648
dr. evil Avatar asked Oct 20 '09 09:10

dr. evil


People also ask

What is the difference between serialize and deserialize JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.

What is Jsonserializer deserialize?

Serialization and deserialization in . NET application, JSON data format conversion to . NET objects and vice versa is very common. Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects.

How does JSON deserialize work?

Deserialization is the process of reversing a String from a previously serialized format. This coverts the serialized String into a format that allows its Data Structure properties to be accessible to manipulation.

What does Jsonconvert Deserializeobject do?

Deserializes the JSON to the specified . NET type. Deserializes the JSON to the specified . NET type using a collection of JsonConverter.


1 Answers

It makes sense to get that error, because an IModel property could refer to different classes and there is no guarantee that they are all Serializable.


OK, I gave it a try and we have a:

Testcase error, it works on my computer.


interface IFoo { }

[Serializable]
class CFoo : IFoo   { }

[Serializable]
class Bar
{
    public IFoo Foo { get; set; }
}

And Bar Serializes and Deserializes fine.

Bar b = new Bar();
b.Foo = new CFoo();

using (var s = new System.IO.MemoryStream())
{
    var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
    bf.Serialize(s, b);
    s.Position = 0;
    b = (Bar)bf.Deserialize(s);

    Console.WriteLine("OK");
}

So, what is different from your IModel and Model?

like image 168
Henk Holterman Avatar answered Oct 09 '22 18:10

Henk Holterman