Skip to content

Instantly share code, notes, and snippets.

@werwolfby
Last active June 27, 2024 17:24
Show Gist options
  • Save werwolfby/5bc3e799d6e0cba8d3ba58ec22af3eea to your computer and use it in GitHub Desktop.
Save werwolfby/5bc3e799d6e0cba8d3ba58ec22af3eea to your computer and use it in GitHub Desktop.
Custom JsonConverter that could fallback to default one
public static class CustomJsonSerializerOptions
{
public static readonly JsonSerializerOptions Options = new() {
PropertyNamingPolicy = new SnakeCaseJsonNamingPolicy(),
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Converters = {
new JsonStringEnumConverter (new SnakeCaseJsonNamingPolicy()),
// Other converters
}
}
private static readonly Dictionary<Type, JsonSerializerOptions> ConverterTypeToRecursionSafeJsonSerializerOptionsMap =
Options.Converters.ToDictionary(c => c.GetType(), c => {
var optionsExcludingConverter = new JsonSerializerOptions(Options);
optionsExcludingConverter.Converters.Remove(c);
return optionsExcludingConverter;
});
public static JsonSerializerOptions GetRecursionSafeJsonSerializerOptions<T>(this T _)
where T : JsonConverter
=> ConverterTypeToRecursionSafeJsonSerializerOptionsMap[typeof(T)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment