Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DotLiquid Hash.FromAnonymousObject with Deserialized JSon Object

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);
like image 363
skysurfer Avatar asked Oct 29 '25 10:10

skysurfer


1 Answers

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));
like image 157
E Rolnicki Avatar answered Oct 31 '25 13:10

E Rolnicki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!