【问题标题】:JObject and DotLiquidJObject 和 DotLiquid
【发布时间】:2019-08-07 15:42:26
【问题描述】:

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

输出:

单条

双栏

但对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();

【问题讨论】:

    标签: c# liquid dotliquid


    【解决方案1】:

    DotLiquid 中似乎没有对 JSON 的直接支持

    获取newtonsoft.json库,先反序列化json;像这样的

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

    Expando 实现了 DotLiquid 支持的 IDictionary。或者,做清​​单

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 2016-11-28
    • 2021-02-22
    • 1970-01-01
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多