101 lines
4.6 KiB
C#
101 lines
4.6 KiB
C#
namespace SOR.Game.Abilities;
|
|
|
|
using System.Reflection;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using SOR.Game.Abilities.Models;
|
|
|
|
/// <summary>
|
|
/// Generic base converter that fixes polymorphic deserialization when the
|
|
/// <c>$type</c> discriminator is not the first property in a JSON object.
|
|
///
|
|
/// System.Text.Json requires <c>$type</c> to appear first for abstract base
|
|
/// classes. Card-definition JSON authored in the admin tool does not guarantee
|
|
/// that ordering. This converter buffers the entire JSON object, finds
|
|
/// <c>$type</c> at any position, looks up the concrete type from the
|
|
/// <see cref="JsonDerivedTypeAttribute"/> map on <typeparamref name="T"/>,
|
|
/// then deserializes via the default converter.
|
|
///
|
|
/// <c>CanConvert</c> returns <c>true</c> <em>only</em> for the exact base type
|
|
/// <typeparamref name="T"/> — not for concrete derived types — so there is no
|
|
/// infinite recursion when the default converter processes derived-type properties.
|
|
/// </summary>
|
|
internal abstract class PolymorphicAbilityConverter<T> : JsonConverter<T> where T : class
|
|
{
|
|
// Static fields are per closed type T — each T gets its own map.
|
|
private static readonly Dictionary<string, Type> s_typeMap;
|
|
private static readonly Dictionary<Type, string> s_reverseMap;
|
|
|
|
static PolymorphicAbilityConverter()
|
|
{
|
|
s_typeMap = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
|
|
s_reverseMap = new Dictionary<Type, string>();
|
|
|
|
foreach (var attr in typeof(T).GetCustomAttributes<PolyTypeAttribute>())
|
|
{
|
|
s_typeMap[attr.Discriminator] = attr.DerivedType;
|
|
// First [PolyType] for a given concrete type wins for writing (canonical discriminator).
|
|
// Additional attributes register read-only aliases for backwards compatibility.
|
|
s_reverseMap.TryAdd(attr.DerivedType, attr.Discriminator);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Only intercept the abstract base <typeparamref name="T"/> itself.
|
|
/// Concrete derived types fall through to the default serializer.
|
|
/// </summary>
|
|
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(T);
|
|
|
|
public override T? Read(
|
|
ref Utf8JsonReader reader,
|
|
Type typeToConvert,
|
|
JsonSerializerOptions options)
|
|
{
|
|
using var doc = JsonDocument.ParseValue(ref reader);
|
|
var root = doc.RootElement;
|
|
|
|
if (!root.TryGetProperty("$type", out var discriminatorProp))
|
|
throw new JsonException($"{typeof(T).Name} object is missing the '$type' discriminator.");
|
|
|
|
var discriminator = discriminatorProp.GetString()
|
|
?? throw new JsonException($"{typeof(T).Name} '$type' discriminator is null.");
|
|
|
|
if (!s_typeMap.TryGetValue(discriminator, out var concreteType))
|
|
throw new JsonException($"Unknown {typeof(T).Name} '$type': '{discriminator}'.");
|
|
|
|
// CanConvert returns false for concrete derived types, so no infinite recursion.
|
|
return (T?)root.Deserialize(concreteType, options);
|
|
}
|
|
|
|
public override void Write(
|
|
Utf8JsonWriter writer,
|
|
T value,
|
|
JsonSerializerOptions options)
|
|
{
|
|
var concreteType = value.GetType();
|
|
if (!s_reverseMap.TryGetValue(concreteType, out var discriminator))
|
|
throw new JsonException($"No '$type' discriminator registered for {concreteType.Name}.");
|
|
|
|
// Serialize the concrete object (CanConvert=false for it → no recursion).
|
|
using var mem = new System.IO.MemoryStream();
|
|
using (var inner = new Utf8JsonWriter(mem))
|
|
JsonSerializer.Serialize(inner, value, concreteType, options);
|
|
|
|
using var doc = JsonDocument.Parse(mem.ToArray());
|
|
|
|
// Write with $type first so round-trip JSON is always well-formed.
|
|
writer.WriteStartObject();
|
|
writer.WriteString("$type", discriminator);
|
|
foreach (var prop in doc.RootElement.EnumerateObject())
|
|
prop.WriteTo(writer);
|
|
writer.WriteEndObject();
|
|
}
|
|
}
|
|
|
|
// ── Concrete converters ───────────────────────────────────────────────────────
|
|
|
|
internal sealed class EffectPolymorphicConverter : PolymorphicAbilityConverter<Effect> { }
|
|
internal sealed class ConditionPolymorphicConverter : PolymorphicAbilityConverter<Condition> { }
|
|
internal sealed class TriggerPolymorphicConverter : PolymorphicAbilityConverter<TriggerEvent>{ }
|
|
internal sealed class FilterPolymorphicConverter : PolymorphicAbilityConverter<Filter> { }
|