23 lines
1013 B
C#
23 lines
1013 B
C#
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);
|
|
}
|