Fix: deserialize polymorphic Effect when $type is not the first JSON property

[JsonPolymorphic] on an abstract base class requires $type to appear first in
the JSON object. Card abilities authored in the admin tool don't guarantee this
ordering (e.g. {"N":1,"$type":"DrawCards","Player":"Owner"}), causing a
NotSupportedException at ParseAbilities time.

Add EffectPolymorphicConverter which overrides CanConvert to intercept only
typeof(Effect) (not concrete derived types). It buffers the full JSON object,
finds $type at any position, looks up the concrete type from the [JsonDerivedType]
attribute map, then deserializes via the default converter. Because CanConvert
returns false for concrete types, there is no infinite recursion even for nested
Effect[] (e.g. ApplyOnEventEffect.Effects).

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 19:51:43 -04:00
co-authored by Claude Happy
parent 1c0ec5fed9
commit 5ed0ec87e3
2 changed files with 106 additions and 1 deletions
@@ -20,7 +20,14 @@ public static class AbilitySystem
private static readonly JsonSerializerOptions _jsonOpts = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() },
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.
new EffectPolymorphicConverter(),
},
};
// ── Parsing ────────────────────────────────────────────────────────────────
@@ -0,0 +1,98 @@
namespace SOR.Game.Abilities;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using SOR.Game.Abilities.Models;
/// <summary>
/// Custom JSON converter for the polymorphic <see cref="Effect"/> hierarchy.
///
/// 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>).
///
/// 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.
/// </summary>
internal sealed class EffectPolymorphicConverter : JsonConverter<Effect>
{
private static readonly Dictionary<string, Type> _typeMap;
private static readonly Dictionary<Type, string> _reverseMap;
static EffectPolymorphicConverter()
{
_typeMap = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
_reverseMap = new Dictionary<Type, string>();
foreach (var attr in typeof(Effect)
.GetCustomAttributes<JsonDerivedTypeAttribute>())
{
if (attr.TypeDiscriminator is string disc)
{
_typeMap[disc] = attr.DerivedType;
_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.
/// </summary>
public override bool CanConvert(Type typeToConvert)
=> typeToConvert == typeof(Effect);
public override Effect? 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.");
var discriminator = discriminatorProp.GetString()
?? throw new JsonException("Effect '$type' discriminator is null.");
if (!_typeMap.TryGetValue(discriminator, out var concreteType))
throw new JsonException($"Unknown Effect '$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);
}
public override void Write(
Utf8JsonWriter writer,
Effect value,
JsonSerializerOptions options)
{
var concreteType = value.GetType();
if (!_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.
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.
writer.WriteStartObject();
writer.WriteString("$type", discriminator);
foreach (var prop in doc.RootElement.EnumerateObject())
prop.WriteTo(writer);
writer.WriteEndObject();
}
}