JObject和DotLiquid

3

我正在开发一个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();
1个回答

3

看起来DotLiquid没有直接支持JSON。

首先获取newtonsoft.json库并反序列化JSON,代码类似于:

var obj = JsonConvert.DeserializeObject<ExpandoObject>(jsonObject, expConverter);

Expando 实现了由 DotLiquid 支持的 IDictionary 接口。或者,建立一个列表。

var model = JsonConvert.DeserializeObject<List<string>>(json);

"expConverter" 会是什么? - Rafael Simonelli
2
@RafaelSimonelli 请查阅文档 https://www.newtonsoft.com/json/help/html/Overload_Newtonsoft_Json_JsonConvert_DeserializeObject.htm - T.S.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接