You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
1.1 KiB
41 lines
1.1 KiB
1 year ago
|
using System.Text.Json;
|
||
1 year ago
|
using System.Text.Json.Serialization;
|
||
1 year ago
|
using StabilityMatrix.Core.Extensions;
|
||
1 year ago
|
|
||
1 year ago
|
namespace StabilityMatrix.Core.Converters.Json;
|
||
1 year ago
|
|
||
|
public class DefaultUnknownEnumConverter<T> : JsonConverter<T> where T : Enum
|
||
|
{
|
||
|
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||
|
{
|
||
|
if (reader.TokenType != JsonTokenType.String)
|
||
|
{
|
||
|
throw new JsonException();
|
||
|
}
|
||
|
|
||
|
var enumText = reader.GetString();
|
||
|
if (Enum.TryParse(typeof(T), enumText, true, out var result))
|
||
|
{
|
||
|
return (T) result!;
|
||
|
}
|
||
|
|
||
|
// Unknown value handling
|
||
|
if (Enum.TryParse(typeof(T), "Unknown", true, out var unknownResult))
|
||
|
{
|
||
|
return (T) unknownResult!;
|
||
|
}
|
||
|
|
||
|
throw new JsonException($"Unable to parse '{enumText}' to enum '{typeof(T)}'.");
|
||
|
}
|
||
|
|
||
|
public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options)
|
||
|
{
|
||
|
if (value == null)
|
||
|
{
|
||
|
writer.WriteNullValue();
|
||
|
return;
|
||
|
}
|
||
|
writer.WriteStringValue(value.GetStringValue());
|
||
|
}
|
||
|
}
|