You can deserialize JSON in a dictionary and then iterate over this dictionary to make substitutions in string of template.
Note that in my example, I use the package Newstonsoft.Json to deserialize the JSON with the answers. This is not necessary, you can use any other serializer, I chose this by custom. It makes no difference in the main idea.
string Transformar(string template, string json)
{
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
string nova = template;
foreach(var par in dict)
{
nova = nova.Replace($"[{par.Key}]", par.Value);
}
return nova;
}
void Main()
{
string json = "{\"Nome\": \"Marconcilio\", \"Data\": \"21/01/18\"}";
string template = "Olá [Nome], Tenha um bom dia ... hoje é [Data] e é seu aniversario";
Console.WriteLine(template);
// Olá [Nome], Tenha um bom dia ... hoje é [Data] e é seu aniversario
Console.WriteLine(Transformar(template, json));
// Olá Marconcilio, Tenha um bom dia ... hoje é 21/01/18 e é seu aniversario
}
See working on . NET Fiddle.
I made "marconcilio" a change to navigation Object in json.
string Transformar(string template, string json)
{
var dict = JsonConvert.DeserializeObject<Dictionary<object, object>>(json);
string nova = template;
foreach(var par in dict)
{
if(par.Value.ToString().Contains ("{"))
{
nova = Transformar(nova, par.Value.ToString());
}
nova = nova.Replace(string.Format("[{0}]", par.Key), par.Value.ToString());
}
return nova;
}
public void Main()
{
string json = "{ \"Nome\": \"Marconcilio\",\"destinatarioDaNotificacao\": {\"Data\": 11},\"Notificacao\": {\"Teste\": \"novo\"}}";
string template = "Olá [Nome], Tenha um bom dia ... hoje é [Data] e é seu aniversario .. [Teste]";
Console.WriteLine(template);
Console.WriteLine(Transformar(template, json));
}
how about using regex?
– Paz
@Paz, can you do this with regex ? and replay the value that contains in Json ?
– Marco Souza
I believe so, just confirm me if the message value is correct and if it is, if it could be modified.
– Paz
Do you want everything to be dynamic? Only having the string "template" and JSON?
– Jéf Bueno
@LINQ, that’s right. in Templete I have the fields that are in json.. and I want to replace them with the value of the Json property.
– Marco Souza