Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 740
Anders Avatar asked Nov 17 '25 03:11

Anders


1 Answers

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);
like image 70
T.S. Avatar answered Nov 19 '25 19:11

T.S.