C# custom serialization of a class with list of interfaces

303 Views Asked by At

I am trying to find a way to serialize and deserialize the ClassToSerialize below built like:

    [Serializable]
    public interface IFoo
    {
    }

    [Serializable]
    public class BaseFoo : IFoo
    {
    }
    [Serializable]
    public class Foo1 : BaseFoo
    {
        public string Foo1_Member1 { get; set; }
        public int Foo1_Member2 { get; set; }
    }
    [Serializable]
    public class Foo2 : BaseFoo
    {
        public IList<IFoo> Foo2_Member3 { get; set; }
        public string Foo2_Member4 { get; set; }
    }
    [Serializable]
    public class ClassToSerialize
    {
        public string Class_Member1;
        public IFoo Foo;
    }

The class will be passed to an API and on deserialization the instances of Foo1 and Foo2 need to be reconstructed and placed into the "Foo" property and down the chain into IList< IFoo > or a similar object.

I've been stuck with this for a day or so and I am out of ideas!

1

There are 1 best solutions below

0
MihaiP. On

For other people trying to do accomplish something similar: I've ended up implementing ISerializable on BaseFoo, Foo1, Foo2 and ClassToSerialize.

I have added a FooType Type field to the interface and implemented it on the base class.

In the implementation I am deserializing first to BaseFoo and then, I'm deserializing again based on type either to Foo1 or Foo2.

I would love to hear a better approach.