I'm developing a system that receives JSON from multiple layouts over a single channel, and the Router class must identify which layout is handled by regular expression and perform deserialization for the correct class.
In the prototype I used if
nested, but I would like a more dynamic solution, I thought of using a keyed dictionary being Regex and the value of the class to be deserialized, but would like help if this would be the best solution implement best) or if another solution would be indicated.
Below is the code I started to develop:
public class Roteador {
internal static RegexOptions regOpcoes = RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled;
internal static string PatternMsg0002 = "\"Event\"(\s)*:(\s)*\"Msg0002\"?";
internal static string PatternMsg0003 = "\"Event\"(\s)*:(\s)*\"Msg0003\"?";
internal static string PatternMsg0003 = "\"Event\"(\s)*:(\s)*\"Msg0004\"?";
internal static Regex regexMsg0002 = new Regex(PatternMsg0002, regOpcoes);
internal static Regex regexMsg0003 = new Regex(PatternMsg0003, regOpcoes);
internal static Regex regexMsg0004 = new Regex(PatternMsg0004, regOpcoes);
internal static Dictionary<Regex, ClasseBase> dicRegex = new Dictionary<Regex, ClasseBase>();
public static void IntegrarMensagem(string mensagem)
{
JsonSerializer serializer = new JsonSerializer();
ClasseBase meuObjeto;
if (regexMsg0002.IsMatch(mensagem))
meuObjeto = (ClasseFilha1)serializer.Deserialize(textoJson, typeof(ClasseFilha1));
else if (regexMsg0003.IsMatch(mensagem))
meuObjeto = (ClasseFilha2)serializer.Deserialize(textoJson, typeof(ClasseFilha2));
else if (regexMsg0004.IsMatch(mensagem))
meuObjeto = (ClasseFilha3)serializer.Deserialize(textoJson, typeof(ClasseFilha3));
}
}