I have a data model where several data classes are defined. This data classes are serialized in a Unity project (namely A) and then sent via TCP to another Unity project (B) which acts as a debugging tool. By the way, A and B only share the data model. To deserialize the json on the tool project, I loop through the list of valid deserializable types (i.e. the classes in the data model) until a valid one is found and reconstructed. But after that, I'm doing an if-else asking which type was actually reconstructed in order to send its data to the appropriate UI controller. This last part is fragile imo, since any change in the data model (add, remove class) implies changing code responsible for deserializing the json, so I want to ask if there is a better way to achieve this. Below is an example test code:
// This is behaviour is running on B, the tool project
void Update()
{
if (gameData == null)
return;
if (Server.GetRecivedAmount() <= 0)
return;
var msg = Server.GetRecived().Item1;
System.Type messageType = null;
object deserializedMessage = null;
// Find which type is represented by the msg string
foreach (System.Type t in deserializableTypes)
{
settings.SerializationBinder = new GeneralBinder(t);
try
{
deserializedMessage = JsonConvert.DeserializeObject(msg, settings);
Debug.Log($"Successful deserialization: {deserializedMessage.GetType()}");
messageType = t;
break;
}
catch (System.Exception e)
{
Debug.Log("Incorrect type: " + e);
}
}
if (messageType == null)
{
Debug.LogWarning($"{name} didn't find any valid message type");
return;
}
if (messageType == typeof(AgentWrapper))
{
var g = deserializedMessage as AgentWrapper;
if(g.type == AgentWrapper.Type.NEW) { }
}
// Here, there will be more and more if checks and I want to avoid that if possible
}