I have some code that I feel like I should be able to shorten incredibly, but I can't figure out how to do it.
I have a base class called Message and may classes that derive from it.
namespace ModalVR {
public class Message {
public string message;
public Message() {
this.message = this.ToString();
}
}
}
The subclasses get converted to JSON, and I have a function that receives this JSON and I need to create the appropriate class. However the function that does it has a huge case statement and I feel that there must be a better way of doing this. This is what that function looks like.
public Message ConstructMessageFromJSON(string JSON) {
string messageName = JsonUtility.FromJson<Message>(JSON).message;
Message derivedMessage = null;
switch(messageName) {
case "ModalVR.GetBatteryInfo": {
derivedMessage = JsonUtility.FromJson<GetBatteryInfo>(JSON);
break;
}
case "ModalVR.GetBatteryInfoResponse": {
derivedMessage = JsonUtility.FromJson<GetBatteryInfoResponse>(JSON);
break;
}
// Many more case statements snipped out
default: {
LogManager.Log("Received unknown message of " + messageName, LogManager.LogLevel.Error);
break;
}
}
return derivedMessage;
}
Is there any way I can replace this huge case statement with something simpler?
Thanks in advance John Lawrie