Update WinApi
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
// File: Utils/JsonEnumConverter.cs
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user