jam*_*son 6 c# regex templates
我拥有的是存储在数据库中的模板,以及在C#中转换为字典的JSON数据.
例:
模板:"嗨{FirstName}"
数据:"{FirstName:'Jack'}"
通过使用正则表达式提取模板中{}内的任何内容,这可以轻松处理一个级别的数据.
我想要的是我希望能够比第一层更深入地了解JSON.
例:
模板:"嗨{姓名:{First}}"
数据:"{姓名:{第一名:'杰克',最后一名:'史密斯'}}"
我应该采取什么方法?(以及从哪个选择开始的一些指导)
我也希望能够遍历模板中的数据,但我根本不知道从哪一个开始!
谢谢堆
我将这样做:
将您的模板更改为此格式Hi {Name.First}
现在创建一个JavaScriptSerializer用于转换 JSON 的Dictionary<string, object>
JavaScriptSerializer jss = new JavaScriptSerializer();
dynamic d = jss.Deserialize(data, typeof(object));
Run Code Online (Sandbox Code Playgroud)
现在,该变量d在字典中包含 JSON 的值。
这样,您就可以针对正则表达式运行模板,以{X.Y.Z.N}递归方式替换为字典的键。
完整示例:
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;
});
}
Run Code Online (Sandbox Code Playgroud)
我没有处理异常(例如找不到值),您可以处理这种情况,如果没有找到则返回匹配的值。m.Value对于原始值或m.Groups[1].Value之间的字符串{}。