I have a the following example classes
public class Item<TMessageType> where TMessageType : ItemMessage
{
public int Prop1 { get; set; }
public string Prop2 { get; set; }
public int MessageType { get; set; }
public TMessageType Message { get; set; }
}
public class ItemMessage
{
public int SomeProperty { get; set; }
}
public class TypeAMessage: ItemMessage
{
public string PropA { get; set; }
}
public class TypeBMessage: ItemMessage
{
public string PropB { get; set; }
}
public class TypeCMessage: ItemMessage
{
public string PropC { get; set; }
}
I will be receiving from a queue of 'Items' as JSON from an external feed and won't know the type of item message until it is received. I can successfully determine the message type via Regex on the raw JSON string and can use that in a switch statement to deserialise the item correctly. e.g.
// get type
...
// deserialise
dynamic item;
switch(messageTypeFromJson)
{
case 0:
item = JsonSerializer.Deserialize<Item<TypeAMessage>>(jsonString);
break;
case 1:
item = JsonSerializer.Deserialize<Item<TypeBMessage>>(jsonString);
break;
case 2:
item = JsonSerializer.Deserialize<Item<TypeCMessage>>(jsonString);
break;
default:
// handle unexpected type
return;
}
// use item
The above code works but it feels messy. I would like to be able to do something closer to the following (which does not work) to split the determination of the type and the deserialisation into separate steps.
Type messageType;
switch(messageTypeFromJson)
{
case 0:
messageType = typeof(TypeAMessage);
break;
case 1:
messageType = typeof(TypeBMessage);
break;
case 2:
messageType = typeof(TypeCMessage);
break;
default:
// handle unexpected type
return;
}
try
{
var item = JsonSerializer.Deserialize<Item<messageType>>(jsonString);
.....
}
catch(..){ ... }
Is there a way to achieve this?