Uwaa/Pleroma/EnumLowerCaseConverter.cs

19 lines
679 B
C#
Raw Permalink Normal View History

2024-12-13 13:25:20 +01:00
namespace Uwaa.Pleroma;
2024-12-11 03:49:46 +01:00
/// <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());
}
}