我正在研究 REST 模拟服务。我使用 DotLiquid。我想将 POST 正文解析为来自 XML 和 JSON 的对象。
DotLiquid 适用于匿名类型,例如
var input = new
{
Body = new { Foos = new[] { new{ Bar = "OneBar" }, new { Bar = "TwoBar" } } }
};
var template = Template.Parse(@"{% for item in Body.Foos %}
{{ item.Bar }}
{% endfor %}");
Console.WriteLine(template.Render(Hash.FromAnonymousObject(input)));
Console.ReadLine();
输出:
OneBar
TwoBar
但是用JObject
做同样的事情不会输出任何东西
var json = "{ 'Foos': [{ 'Bar': 'OneBar' }, { 'Bar': 'TwoBar' }] }";
var input = new
{
Body = JObject.Parse(json)
};
var template = Template.Parse(@"{% for item in Body.Foos %}
{{ item.Bar }}
{% endfor %}");
Console.WriteLine(template.Render(Hash.FromAnonymousObject(input)));
Console.ReadLine();
最佳答案
看起来 DotLiquid 中没有直接支持 JSON
先获取newtonsoft.json库,反序列化json;像这样的东西
var obj = JsonConvert.DeserializeObject<ExpandoObject>(jsonObject, expConverter);
Expando
实现了 DotLiquid 支持的 IDictionary
。或者,做清单
var model = JsonConvert.DeserializeObject<List<string>>(json);
关于c# - JObject 和 DotLiquid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57398039/