StubbleOrg / Stubble

Trimmed down {{mustache}} templates in .NET
Other
399 stars 58 forks source link

Please add Extensions Setting Support for system.text.json #142

Open SangamMashal opened 1 year ago

SangamMashal commented 1 year ago

Please provide the extension support for [System.text.Json serilization] (https://learn.microsoft.com/en-us/dotnet/api/system.text.json?view=net-7.0) as in documentation only support for System.Data or Newtonsoft.Json

ljani commented 1 year ago

Here's an implementation copied from Stubble.Extensions.JsonNet with the following differences:

public static class StubbleJson
{
    public static RendererSettingsBuilder AddSystemTextJson(this RendererSettingsBuilder builder)
    {
        foreach (var getter in ValueGetters)
        {
            builder.AddValueGetter(getter.Key, getter.Value);
        }

        builder.AddSectionBlacklistType(typeof(JsonElement));

        return builder;
    }

    public static readonly Dictionary<Type, RendererSettingsDefaults.ValueGetterDelegate> ValueGetters = new()
    {
        {
            typeof (JsonElement), (value, key, ignoreCase) =>
            {
                var token = (JsonElement)value;
                var comparison =
                    ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
                JsonProperty childToken = token.EnumerateObject().FirstOrDefault(o => string.Equals(o.Name, key, comparison));

                var childValue = childToken.Value;
                return childValue.ValueKind switch {
                    JsonValueKind.Array => childValue.EnumerateArray(),
                    JsonValueKind.Object => childValue,
                    JsonValueKind.Undefined or JsonValueKind.Null => null,
                    JsonValueKind.String => childValue.GetString(),
                    JsonValueKind.Number => childValue.GetDecimal(),
                    JsonValueKind.True => true,
                    JsonValueKind.False => false,
                };
            }
        },
    };
}