Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize an interface such as IList<T> [duplicate]

Possible Duplicate:
How to serialize an IList<T>?

I wish to serialize an class (let's call it S) that contains a property of the type IList<T> where T is another class which I have defined. I get an exception when I attempted to serialize an instance of class S to XML. This is understandable as the XmlSerializer doesn't know which concrete class to use. Is there a way, hopefully using attributes, to specify which concrete class to instantiate when serializing/deserializing an instance. My implementation of class S creates a instance of the List<T> class. Here is some code to illustrate my example:

using System;
using System.Xml.Serialization;
using System.IO;

[Serializable]
public class T { }

[Serializable]
public class S
{
    public IList<T> ListOfTs { get; set; }

    public S()
    {
        ListOfTs = new List<T>();
    }
}

public class Program
{
    public void Main()
    {
        S s = new S();
        s.ListOfTs.Add(new T());
        s.ListOfTs.Add(new T());
        XmlSerializer serializer = new XmlSerializer(typeof(S));
        serializer.Serialize(new StringWriter(), s);
    }
}

I'm hoping there's an attribute I can place above the ListOfTs definition that says to the serialize, "assume an instance of List<T> when serializing/deserializing".

like image 498
Dan Stevens Avatar asked Apr 04 '12 14:04

Dan Stevens


People also ask

Are interfaces serializable?

The Serializable interface is present in java.io package. It is a marker interface. A Marker Interface does not have any methods and fields. Thus classes implementing it do not have to implement any methods.

What is XML serialization?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.

What is the correct way of using XML deserialization?

To deserialize the objects, call the Deserialize method with the FileStream as an argument. The deserialized object must be cast to an object variable of type PurchaseOrder . The code then reads the values of the deserialized PurchaseOrder .


1 Answers

Change the

public IList<T> ListOfTs { get; set; }

to

public List<T> ListOfTs { get; set; }

Then it will work.

like image 114
Azhar Khorasany Avatar answered Sep 18 '22 13:09

Azhar Khorasany