Init
This commit is contained in:
22
Prefab.Base/PrefabEnumJsonConverter.cs
Normal file
22
Prefab.Base/PrefabEnumJsonConverter.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Prefab.Base;
|
||||
|
||||
/// <summary>
|
||||
/// Serializes <see cref="PrefabEnum{TEnum}"/> values as their logical names and deserializes by name or value.
|
||||
/// </summary>
|
||||
/// <typeparam name="TEnum">Enumeration type to convert.</typeparam>
|
||||
public class PrefabEnumJsonConverter<TEnum> : JsonConverter<TEnum> where TEnum : PrefabEnum<TEnum>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => reader.TokenType switch
|
||||
{
|
||||
JsonTokenType.String => PrefabEnum<TEnum>.FromName(reader.GetString()!),
|
||||
JsonTokenType.Number => PrefabEnum<TEnum>.FromValue(reader.GetInt32()),
|
||||
_ => throw new JsonException($"Unsupported token type '{reader.TokenType}' for Prefab enum deserialization.")
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options) => writer.WriteStringValue(value.Name);
|
||||
}
|
||||
Reference in New Issue
Block a user