Uwaa/Pleroma/EnumLowerCaseConverter.cs
2024-12-13 12:25:20 +00:00

19 lines
No EOL
679 B
C#

namespace Uwaa.Pleroma;
/// <summary>
/// Converts to and from enum values in lowercase.
/// </summary>
class EnumLowerCaseConverter<T> : JsonConverter<T> where T : struct
{
public override bool CanConvert(Type typeToConvert) => typeToConvert.IsEnum;
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return Enum.Parse<T>(reader.GetString() ?? throw new NullReferenceException("Expected a string, got null"), true);
}
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString()?.ToLowerInvariant());
}
}