I have a "wrapper"-class for a list that contains different types of events. The list itself therefore uses a general "AnEvent" interface instead of a concrete type.
public class EventLog
{
[JsonProperty()]
private List<AnEvent> events;
// note that the list is private and has no getter/setter
}
The interface looks like this:
//public enum EventTypes { EventA, EventB };
public interface AnEvent
{
EventTypes EventType
{
get;
set;
}
// some other properties...
}
Last but not least, a concrete event type could look like this:
public class ConcreteEventA : AnEvent
{
private EventTypes eventType = EventTypes.EventA;
public EventTypes EventType
{
get { return eventType; }
set { eventType = value; }
}
// ...
}
public class ConcreteEventB : Event
{
// ....
}
As you can see, the information on the type of the event is a bit redundant here (there is the type of the class itself, e.g. ConcreteEventA, and there is a property called EventType (enum) inside the class).
The serialization of an EventLog-object works fine and returns a JSON-list of events. The type of the events is represented like that: "EventType": 0 (it is "EventA" of the enum).
But I'm having trouble to deserialize the JSON back to an EventLog-instance ("Type is an interface or abstract class and cannot be instantiated"). Of course, it is absolutely clear that the deserialzer cannot determine the needed type of each event in the list. But since I'm having the information of the type due to the EventType-property (which in this case is 0 or 1), I'm wondering how I could use that information to deserialize the whole thing properly.
Thank you.
Well, it is not JSON.Net but with the System.Web.Script.Serialization.JavaScriptSerializer you can use a SimpleTypeResolver to map your derived type to the interface.
With JSON.Net it seems this could be achieved with an IContractResolver which gives you access to treat levels of serialization and deserialization with custom behaviour.
It seems both of these methods would require something (like an extra property indicating type) to be inserted into the JSON during serialization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With