Fix: extend $type-anywhere deserialization to Condition, TriggerEvent, and Filter

Refactor EffectPolymorphicConverter into a generic PolymorphicAbilityConverter<T>
base class, add concrete converters for all four abstract ability model types:
Effect, Condition, TriggerEvent, and Filter — all share the same abstract +
[JsonPolymorphic] pattern and the same ordering constraint from the admin builder.

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-03-09 20:17:01 -04:00
co-authored by Claude Happy
parent 5ed0ec87e3
commit 51a7f9e8d2
2 changed files with 50 additions and 44 deletions
@@ -23,10 +23,13 @@ public static class AbilitySystem
Converters =
{
new System.Text.Json.Serialization.JsonStringEnumConverter(),
// Handles polymorphic Effect deserialization when $type is not the first
// property — the default [JsonPolymorphic] behavior requires $type first
// for abstract base types.
// Handle polymorphic deserialization when $type is not the first property.
// The default [JsonPolymorphic] behavior requires $type first for abstract
// base types; admin-tool JSON does not guarantee that ordering.
new EffectPolymorphicConverter(),
new ConditionPolymorphicConverter(),
new TriggerPolymorphicConverter(),
new FilterPolymorphicConverter(),
},
};
@@ -6,89 +6,85 @@ using System.Text.Json.Serialization;
using SOR.Game.Abilities.Models;
/// <summary>
/// Custom JSON converter for the polymorphic <see cref="Effect"/> hierarchy.
/// Generic base converter that fixes polymorphic deserialization when the
/// <c>$type</c> discriminator is not the first property in a JSON object.
///
/// Problem: <see cref="System.Text.Json"/> requires the <c>$type</c> discriminator to be
/// the <em>first</em> property in the JSON object when the base class is abstract.
/// Card-definition JSON authored in the admin tool does not guarantee that ordering
/// (e.g. <c>{"N":1,"$type":"DrawCards","Player":"Owner"}</c>).
/// 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.
///
/// Fix: this converter intercepts only <c>typeof(Effect)</c> (not derived types —
/// see <see cref="CanConvert"/>), reads the entire JSON object into a
/// <see cref="JsonDocument"/>, finds <c>$type</c> regardless of position, then
/// deserializes into the correct concrete type. Concrete derived types are handled
/// by the standard serializer so there is no infinite recursion.
/// <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 sealed class EffectPolymorphicConverter : JsonConverter<Effect>
internal abstract class PolymorphicAbilityConverter<T> : JsonConverter<T> where T : class
{
private static readonly Dictionary<string, Type> _typeMap;
private static readonly Dictionary<Type, string> _reverseMap;
// 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 EffectPolymorphicConverter()
static PolymorphicAbilityConverter()
{
_typeMap = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
_reverseMap = new Dictionary<Type, string>();
s_typeMap = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
s_reverseMap = new Dictionary<Type, string>();
foreach (var attr in typeof(Effect)
.GetCustomAttributes<JsonDerivedTypeAttribute>())
foreach (var attr in typeof(T).GetCustomAttributes<JsonDerivedTypeAttribute>())
{
if (attr.TypeDiscriminator is string disc)
{
_typeMap[disc] = attr.DerivedType;
_reverseMap[attr.DerivedType] = disc;
s_typeMap[disc] = attr.DerivedType;
s_reverseMap[attr.DerivedType] = disc;
}
}
}
/// <summary>
/// Only intercept the abstract base <see cref="Effect"/> itself.
/// Concrete derived types (e.g. <c>DrawCardsEffect</c>) fall through to the
/// default serializer — this prevents infinite recursion.
/// 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(Effect);
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(T);
public override Effect? Read(
ref Utf8JsonReader reader,
Type typeToConvert,
public override T? Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options)
{
// Buffer the entire object so we can find $type anywhere.
using var doc = JsonDocument.ParseValue(ref reader);
var root = doc.RootElement;
if (!root.TryGetProperty("$type", out var discriminatorProp))
throw new JsonException("Effect object is missing the '$type' discriminator.");
throw new JsonException($"{typeof(T).Name} object is missing the '$type' discriminator.");
var discriminator = discriminatorProp.GetString()
?? throw new JsonException("Effect '$type' discriminator is null.");
?? throw new JsonException($"{typeof(T).Name} '$type' discriminator is null.");
if (!_typeMap.TryGetValue(discriminator, out var concreteType))
throw new JsonException($"Unknown Effect '$type': '{discriminator}'.");
if (!s_typeMap.TryGetValue(discriminator, out var concreteType))
throw new JsonException($"Unknown {typeof(T).Name} '$type': '{discriminator}'.");
// Deserialize as the concrete type. CanConvert returns false for concrete
// types, so this call uses the default converter — no recursion.
return (Effect?)root.Deserialize(concreteType, options);
// CanConvert returns false for concrete derived types, so no infinite recursion.
return (T?)root.Deserialize(concreteType, options);
}
public override void Write(
Utf8JsonWriter writer,
Effect value,
T value,
JsonSerializerOptions options)
{
var concreteType = value.GetType();
if (!_reverseMap.TryGetValue(concreteType, out var discriminator))
if (!s_reverseMap.TryGetValue(concreteType, out var discriminator))
throw new JsonException($"No '$type' discriminator registered for {concreteType.Name}.");
// Serialize the concrete object first to get its properties as a JsonDocument.
// CanConvert returns false for concrete types, so no recursion.
// 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 the final object: $type first, then all concrete properties.
// 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())
@@ -96,3 +92,10 @@ internal sealed class EffectPolymorphicConverter : JsonConverter<Effect>
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> { }