⚙️ Asp.Net Core: Fix JSON Source Generation Skipping a Derived Type
System.Text.Json’s source generator only emits serialization code for the exact set of types it’s told about at compile time through a JsonSerializerContext, which means polymorphic serialization of a base type needs every concrete subtype declared explicitly via JsonDerivedType. Add a new subtype later without updating that attribute list, and serializing a collection of the base type doesn’t throw — it just serializes each new-subtype instance using only the base type’s own properties, silently dropping every field the subtype added.
🔎 The Problem
[JsonPolymorphic]
[JsonDerivedType(typeof(EmailNotification), "email")]
[JsonDerivedType(typeof(SmsNotification), "sms")]
public abstract class Notification { public string UserId { get; set; } }
// Added later, but the attribute list above was never updated:
public class PushNotification : Notification
{
public string DeviceToken { get; set; }
}
// Serializing a List<Notification> containing a PushNotification
// drops DeviceToken entirely - no exception, no warning
✅ Fix: Keep the Derived-Type List and Tests in Lockstep With the Hierarchy
- Add a
[JsonDerivedType]entry for every concrete type the moment it’s created, as part of the same change that adds the class, rather than treating it as a separate follow-up step. - Write a round-trip test per derived type that serializes through the actual generated
JsonSerializerContextand asserts every derived-only property survives, so a missing registration fails a test instead of shipping silently. - Where the type hierarchy changes often, consider a small analyzer or a reflection-based startup check that compares every non-abstract subtype against the registered
JsonDerivedTypelist and fails fast if one is missing.
🚨 Why This Is Dangerous
- Losing a field only during polymorphic serialization, with the type’s own direct serialization working fine, is exactly the kind of bug that passes unit tests on the concrete type and only shows up once that type is serialized as part of a mixed collection in production.
A source generator can only serialize the types it was told about — adding a new subtype to your hierarchy doesn’t add it to the generator’s list for free.
