[Question] How can I work with #if and objects loaded from JSON?
utillity opened this issue · 3 comments
#if
does not work correctly with objects loaded from json, as autoRenew
is not a Boolean
but a JValue
.
If I run this code, the #if
statement works (ie. interprets autoRenew
as Boolean
) correctly:
var context = new { ctx = new { grant = new { autoRenew = true } } };
var template = "ctx.grant.autoRenew={{ctx.grant.autoRenew}} {{#if ctx.grant.autoRenew}}will auto-renew{{else}}will expire{{/if}}";
var merger = Handlebars.Compile(template);
var result = merger((object)context);
output.WriteLine(result);
output.WriteLine("\n\n\n");
output.WriteLine(((object)context).ToJson(true));
result.Should().NotContain("will expire", "AutoRenew is set to true");
output
autoRenew=True (Boolean)
ctx.grant.autoRenew=True will auto-renew
{
"ctx": {
"grant": {
"autoRenew": true
}
}
}
But if I load the context from JSON, the #if
block will not interpret the JValue as Boolean
and will return the ELSE
block.
Not working example
var contextJson = @"{ ""ctx"": { ""grant"": { ""autoRenew"": true } } }";
var context = contextJson.FromJson<dynamic>();
...
output
autoRenew=True (JValue)
ctx.grant.autoRenew=True will expire
{
"ctx": {
"grant": {
"autoRenew": true
}
}
}
Any idea how I can fix this?
The core handlebars.net engine does not know about JSON.NET or its special types like JValue, but https://github.com/Handlebars-Net/Handlebars.Net.Extension.NewtonsoftJson adds support. Try using that.
Or try using a JSON parsing method that produces POCOs and not the Newtonsoft-type structure.
thanks for the quick response! Deserializing to ExpandoObject
instead of Dynamic
works! Will see if the extension is of any use as well, thanks!