Last active
June 27, 2024 17:24
-
-
Save werwolfby/5bc3e799d6e0cba8d3ba58ec22af3eea to your computer and use it in GitHub Desktop.
Custom JsonConverter that could fallback to default one
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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