Stubble
Stubble copied to clipboard
Please add Extensions Setting Support for system.text.json
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
Here's an implementation copied from Stubble.Extensions.JsonNet
with the following differences:
- It returns
decimal
for all numbers - It will not parse
DateTime
s
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,
};
}
},
};
}