I need to implement remote connectivity for an existing reporting interface, which requires serialisation and de-serialisation of the data classes. Here is a simplified version of the classes and interfaces:
public interface IBase
{
string Name { get; }
}
public interface IDerived1
{
int Value { get; }
}
public interface IDerived2
{
bool Value { get; }
}
public class Base : IBase
{
public string Name { get; protected set; }
}
public class Derived1 : Base, IDerived1
{
public int Value { get; protected set; }
}
public class Derived2 : Base, IDerived2
{
public bool Value { get; protected set; }
}
As a input parameter I get
IEnumerable<IBase> reportingData
So this collection may contain any number and combination of instances of 'Derived1' and 'Derived2'. I then serialise the collection like this:
string serialisedReportingData = JsonConvert.SerializeObject( reportingData );
Which gives me for example this:
[{"Value":11,"Name":"Product Number"},{"Value":false,"Name":"Output 1 Enabled"}]
Obviously with this data alone, de-serialisation is impossible, as the type of the individual collection entries is not in the JSON. I could for example make the type part of the JSON or provide an additional collection of types for use during de-serialisation.
I have used CustomCreationConverter overloads before to deal with
JsonConvert.DeserializeObject<IEnumerable<Ixxx>>( ... );
type of scenarios, but this only applied to a single interface type inside the IEnumerable. In my example above I have two: IDerived1 and IDerived2.
My questions / issues:
a) I am not sure how a CustomCreationConverter could be written that deals with more than one interface type and I don't know how to get the type into this.
b) I would love your suggestions on how to implement a solution that would give me the same de-serialisation output as the 'IEnumerable reportingData' I received as input.
I would much appreciate a working code example, where possible.
Many thanks in advance, Christian