Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
SangamMashal opened this issue Dec 19, 2022 · 1 comment
Open

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

SangamMashal opened this issue Dec 19, 2022 · 1 comment

Comments

@SangamMashal
Copy link

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
Copy link

ljani commented Jun 27, 2023

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

  • It returns decimal for all numbers
  • It will not parse DateTimes
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,
                };
            }
        },
    };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants