1
I am developing a system that receives JSON from several layouts for a single channel and the Router class must identify which layout is by regular expression and perform the deserialization for the correct class.
In the prototype I used if
nested, but would like a more dynamic solution, thought to use dictionary with key being the Regex and the value the class to be deserialized, but would like help if this would be the best solution (and how best to implement) or if another solution would be indicated.
Below 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));
}
}