winmr-api/Utils/JsonEnumConverter.cs

56 lines
1.8 KiB
C#
Raw Normal View History

2025-07-04 00:04:51 +03:00
/* This software is licensed by the MIT License, see LICENSE file */
/* Copyright © 2024-2025 Gregory Lirent */
2025-07-02 18:13:00 +03:00
using System.Text.Json;
using System.Text.Json.Serialization;
namespace WebmrAPI.Utils
{
public class JsonEnumConverter<T> : JsonConverter<T> where T : Enum
{
private T GetDefaultValue(Type type)
{
if (Enum.TryParse(type, "Undefined", true, out object? result) && result != null)
{
return (T)result;
}
return (T)Enum.ToObject(type, 0);
}
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
{
if (Enum.TryParse(typeToConvert, reader.GetString(), true, out object? result) && result != null)
{
return (T)result;
}
}
else if (reader.TokenType == JsonTokenType.Number)
{
if (reader.TryGetInt32(out int intValue))
{
T status = (T)Enum.ToObject(typeToConvert, intValue);
if (Enum.IsDefined(typeof(T), status))
{
return status;
}
}
}
return GetDefaultValue(typeToConvert);
}
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
if (Enum.IsDefined(typeof(T), value))
{
writer.WriteStringValue(value.ToString());
}
else
{
writer.WriteStringValue("Undefined");
}
}
}
}