Here's how I do it:
Change your template in this format Hi {Name.First}
Now create a JavaScriptSerializer to convert JSON to Dictionary<string, object>
JavaScriptSerializer jss = new JavaScriptSerializer(); dynamic d = jss.Deserialize(data, typeof(object));
Now the variable d has the values โโof your JSON in the dictionary.
After that, you can run the pattern against the regular expression to replace {XYZN} with dictionary keys, recursively.
Full example:
public void Test() { // Your template is simpler string template = "Hi {Name.First}"; // some JSON string data = @"{""Name"":{""First"":""Jack"",""Last"":""Smith""}}"; JavaScriptSerializer jss = new JavaScriptSerializer(); // now `d` contains all the values you need, in a dictionary dynamic d = jss.Deserialize(data, typeof(object)); // running your template against a regex to // extract the tokens that need to be replaced var result = Regex.Replace(template, @"{?{([^}]+)}?}", (m) => { // Skip escape values (ex: {{escaped value}} ) if (m.Value.StartsWith("{{")) return m.Value; // split the token by `.` to run against the dictionary var pieces = m.Groups[1].Value.Split('.'); dynamic value = d; // go after all the pieces, recursively going inside // ex: "Name.First" // Step 1 (value = value["Name"]) // value = new Dictionary<string, object> // { // { "First": "Jack" }, { "Last": "Smith" } // }; // Step 2 (value = value["First"]) // value = "Jack" foreach (var piece in pieces) { value = value[piece]; // go inside each time } return value; }); }
I did not handle exceptions (for example, the value could not be found), you can handle this case and return the associated value if it was not found. m.Value for the original value or m.Groups[1].Value for the line between {} .
source share