Darf Zon
Darf Zon

Reputation: 6378

How to serialize and deserialize an interface using IXmlSerializer?

I'm trying to serialize an interface. I know that this is impossible throught the standart serialization, that's the reason why I used the custom serialization in a base class.

public interface IFoo 
{ 
    object Value { get; } 
} 

public abstract class Foo<T> : IFoo, IXmlSerializable 
{ 
    [XmlElement] 
    public T Value { get; set; } 
    [XmlIgnore] 
    object IFoo.Value { get { return Value; } } 

    XmlSchema IXmlSerializable.GetSchema() { return null; } 
    void IXmlSerializable.ReadXml(XmlReader reader) { throw new NotImplementedException(); } 
    void IXmlSerializable.WriteXml(XmlWriter writer) 
    { 
        XmlSerializer serial = new XmlSerializer(Value.GetType()); 
        serial.Serialize(writer, Value); 
    } 
} 

public class FooA : Foo<string> { } 
public class FooB : Foo<int> { } 
public class FooC : Foo<List<Double>> { } 
public class FooContainer : List<IFoo>, IXmlSerializable 
{ 
    public XmlSchema GetSchema() { return null; } 
    public void ReadXml(XmlReader reader) { throw new NotImplementedException(); }  
    public void WriteXml(XmlWriter writer) 
    { 
        ForEach(x =>  
            { 
                XmlSerializer serial = new XmlSerializer(x.GetType()); 
                serial.Serialize(writer, x); 
            }); 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
        FooContainer fooList = new FooContainer() 
        { 
            new FooA() { Value = "String" }, 
            new FooB() { Value = 2 }, 
            new FooC() { Value = new List<double>() {2, 3.4 } }  
        }; 

        XmlSerializer serializer = new XmlSerializer(fooList.GetType(), 
            new Type[] { typeof(FooA), typeof(FooB), typeof(FooC) }); 
        System.IO.TextWriter textWriter = new System.IO.StreamWriter(@"C:\temp\demo.xml"); 
        serializer.Serialize(textWriter, fooList); 
        textWriter.Close(); 
    } 
} 

My custom serializations are not correct. By the moment is saving for all the property Value, but to deserialized I really have no idea how to do this.

The idea is to save the property Value and to recover the fooContainer with the elements.

Upvotes: 0

Views: 1558

Answers (1)

C.Evenhuis
C.Evenhuis

Reputation: 26446

A deserializer would not only deserialize the property values, but also the object containing them. That object cannot be of type IMyInterface as it is an interface and cannot be instantiated. You'll want to serialize an implementation of that interface, and deserialize it, or assign a default implementation of the interface to deserialize into.

Upvotes: 1

Related Questions