0

I am trying to implement a way to save a set of objects to file, and then read it back to objects again. I want to serialize the objects to XML (or JSON). The objects consists of one master object which holds an array of all the other objects. The array is of the type Interface, to allow several different types of child objects with some common functionality. Obviously, there will be a problem during deserialization because the type of the interface object is not known.

Example:

    [Serializable]
    public class MasterClass
    {
        public ImyInterface[] subObjects;
    }
    public interface ImyInterface
    {

    }

How can I serialize/deserialize these objects?

My suggestions: Add information about the object type in the serialized data. Use a different solution than interface.

1

2 Answers 2

1

This is not the only way to serialize your data, but it is a ready to use solution from the framework:

DataContractSerializer supports this is you don't mind adding attributes for each of the available implementations of the interface:

[DataContract]
[KnownType(typeof(MyImpl))] // You'd have to do this for every implementation of ImyInterface
public class MasterClass
{
    [DataMember]
    public ImyInterface[] subObjects;
}

public interface ImyInterface
{

}

public class MyImpl : ImyInterface
{
    ...
}

Serializing/deserializing:

MasterClass mc = ...

using (var stream = new MemoryStream())
{
    DataContractSerializer ser = new DataContractSerializer(typeof(MasterClass));
    ser.WriteObject(stream, mc);

    stream.Position = 0;
    var deserialized = ser.ReadObject(stream);
}

For JSON you could use DataContractJsonSerializer instead.

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

Comments

0

One solution is to use an abstract class instead of an interface:

public class MasterClass
{
    public MyAbstractClass[] subObjects;
}

[XmlInclude(typeof(MyImpl ))] //Include all classes that inherits from the abstract class
public abstract class MyAbstractClass
{

}

public class MyImpl : MyAbstractClass
{
    ...
}

It can be serialized/deserialized with the XmlSerializer:

MasterClass mc = ...

using (FileStream fs = File.Create("objects.xml"))
{
    xs = new XmlSerializer(typeof(MasterClass));
    xs.Serialize(fs, mc);
}


using (StreamReader file = new StreamReader("objects.xml"))
{
    XmlSerializer reader = new XmlSerializer(typeof(MasterClass));
    var deserialized = reader.Deserialize(file);
}

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.