2

I want to use DotLiquid to create HTML in my ASP Net Core 2.2 Project

My data source comes from a JSon string which is passed to the method.

After deserializing the string with DeserializeObject I get an error in the Hash.FromAnonymousObject method

This works:

var stuff1 = new
{
    Name = "John",
    Surname = "Smith",
    Addresses = new[] {
        new { City = "New York", State = "NY"},
        new { City = "Milano", State = "IT" }
    }
};
var hash1 = DotLiquid.Hash.FromAnonymousObject(stuff1);

This give me the error Incorrect number of arguments supplied for call to method 'Newtonsoft.Json.Linq.JToken get_Item(System.Object)' Parameter name: property

dynamic stuff2 = JsonConvert.DeserializeObject("{
'Name': 'John', 'Surname': 'Smith',
'Addresses': [
    { 'City': 'New York', 'State': 'NY' },
    { 'City': 'Milano', 'State': 'IT' }
]}");
var hash2 = DotLiquid.Hash.FromAnonymousObject(stuff2);
skysurfer
  • 721
  • 2
  • 5
  • 23
  • are you able to resolve this issue? are you able to bind collection. For example `{{Addresses[0].City}}` – LP13 Feb 03 '21 at 21:22

1 Answers1

2

DotLiquid has an alternative Hash generator from Dictionary. I was just able to solve this, with complex json structures, leveraging that by doing the following:

include the following:

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

then (for brevity the json is simple below, but works for complex structures, with nontrivial liquid templates)

    string template = "<h4>hello {{name}}</h4>";
    string json = "{ \"name\" : \"john doe\"}";
    dynamic expandoObj = JsonConvert.DeserializeObject<ExpandoObject>(json, new ExpandoObjectConverter());
IDictionary<string, object> expandoDict = new Dictionary<string, object>(expandoObj);

var liquidTemplate = DotLiquid.Template.Parse(template);
var result = liquidTemplate.Render(Hash.FromDictionary(expandoDict));
E Rolnicki
  • 1,677
  • 2
  • 17
  • 26
  • This does not work when object is inside the collection https://stackoverflow.com/questions/66033550/dotliquid-cannot-bind-property-of-an-object-inside-an-array – LP13 Feb 03 '21 at 20:22