Search code examples
c#liquiddotliquid

JObject and DotLiquid


I'm working on a REST mock service. I use DotLiquid. I want to parse POST body into a object from XML and JSON.

DotLiquid works with anonymous types, like

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

Output:

OneBar

TwoBar

But doing the same with JObject does not output anything

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

Solution

  • Looks like there is no direct support for JSON in DotLiquid

    Get newtonsoft.json library and deserialize json first; something like this

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

    Expando implements IDictionary supported by DotLiquid. Or, do the list

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