November 23, 2026

The Evolution of Polymorphic Serialization: Why System.Text.Json Offers a Safer Path for Obfuscated .NET Applications

In the landscape of .NET development, maintaining the integrity of serialized data is often viewed as a routine task. Developers are well-acquainted with the minor inconveniences of property-level renaming breaks—those instances where a JSON key comes out incorrectly after a build, only to be quickly corrected with a [JsonPropertyName] attribute. These issues are generally considered shallow, cosmetic, and easily remediated. However, a much deeper and more catastrophic hazard exists within the realm of polymorphic serialization, where the stakes transition from minor wire-format mismatches to the total loss of historical data readability.

The core of the issue lies in how a system identifies a type during the serialization process. When dealing with polymorphism—such as a list containing various derived types like circles and rectangles stored under a base "shape" reference—the serializer must encode the identity of the concrete type itself. In many legacy configurations, this identity is inextricably linked to the Common Language Runtime (CLR) type name. When code obfuscation is introduced into the pipeline, its primary objective is to destroy that very identity to protect intellectual property. This creates a fundamental conflict: the obfuscator renames the type to an unintelligible string, while the serializer remains dependent on the original name to reconstruct the object.

Recent analysis of modern .NET design reveals that this vulnerability is not an inherent flaw of serialization, but rather a consequence of specific design choices. While legacy tools like Newtonsoft.Json often default to patterns that are fragile under obfuscation, the modern System.Text.Json library provides a framework that is "safe by construction." By moving away from CLR-bound identities and toward developer-owned discriminators, the industry is seeing a shift toward more resilient data persistence strategies.

Two Philosophies of Type Encoding

To understand why some systems fail where others succeed, one must examine the two fundamentally different ways to encode a type on the wire. The legacy approach, exemplified by Newtonsoft’s TypeNameHandling, relies on writing the assembly-qualified name of the CLR type directly into the JSON metadata. For instance, a "Circle" object might be serialized with a metadata property like $type set to "MyApp.Shapes.Circle, MyApp".

On the surface, this approach is highly flexible. It allows the serializer to resolve the string back to a functional Type via the equivalent of a Type.GetType call. However, this convenience welds the wire format to the internal CLR identity. The moment that identity changes—whether through refactoring or obfuscation—the link is severed.

In contrast, the System.Text.Json approach, utilizing the [JsonDerivedType] attribute, decouples the wire format from the internal class name. Instead of relying on the compiler’s name for a class, the developer explicitly chooses a discriminator—a literal string like "circle" or "rect". When the system reads this discriminator, it performs a lookup in a registration table built from attributes to find the corresponding type. In this model, the wire format is welded to a string owned by the developer, not a name owned by the compiler or modified by an obfuscator.

The Impact of Obfuscation on Serialization Integrity

The divergence between these two designs becomes starkly apparent when an obfuscator is introduced into the build process. Obfuscation works by consistently rewriting type names and metadata tokens throughout an assembly. Every reference to a class—whether it be a method call, a field type, or a typeof expression—is updated to point to the new, renamed entity. This transparency allows ordinary code to function perfectly despite the name changes.

However, the success of this process depends on whether the serialization format relies on a metadata token or a raw string. Because Newtonsoft’s TypeNameHandling reads a name, obfuscation breaks the system in two distinct ways. First, any documents persisted before the renaming occurred will contain the original, cleartext type names. When the obfuscated application attempts to load these documents, it searches for types that no longer exist under those names, resulting in a JsonSerializationException.

Second, any documents written by the obfuscated application will embed the new, mangled names (such as a.b). This creates a "leaky abstraction" where the internal rename map of a specific build is exposed in the persisted data. This effectively couples the data to a single, specific build version, making long-term data migration a nightmare and exposing the very identities the developer sought to hide.

System.Text.Json avoids these pitfalls through its use of discriminators. Because the [JsonDerivedType] attribute maps the stable literal string "circle" to a metadata token, the obfuscator can safely rename the Circle class. The renamer updates the metadata token to point to the new class name, but the literal string "circle" remains unchanged in the attribute. Consequently, the byte-for-byte output on the wire remains identical before and after obfuscation. A document written a year ago will still deserialize correctly on a build produced today, regardless of how aggressively the internal types have been renamed.

The Risks of the "nameof" Anti-pattern

Despite the safety offered by modern serialization attributes, there remains one common practice that can undermine the entire design: the use of the nameof operator. Many developers, in an effort to avoid "magic strings" and ensure refactoring safety, use typeDiscriminator: nameof(Circle).

While this appears clean, it inadvertently re-couples the public wire format to the original class name. While the nameof operator is resolved at compile-time and will not technically "break" the serialization after a rename (the wire will still say "Circle"), it creates a significant security and privacy leak. In a scenario where an organization is paying for obfuscation to protect its internal logic, using nameof ensures that the JSON payloads continue to advertise sensitive type names like PremiumSubscription, AdminCommand, or InternalAuditLog.

Security experts recommend the use of opaque, intentional discriminators. By choosing a wire vocabulary that is independent of the code—such as "s1" for a shape or "cmd_01" for a command—developers can ensure that their public-facing data provides no roadmap for potential attackers. This principle extends to the discriminator property name itself; developers are encouraged to use stable strings like "kind" or the default "$type" rather than deriving names from class members.

Streamlining the Obfuscation Pipeline

One of the most significant advantages of the discriminator-based design is the reduction in complexity for build pipelines. In legacy systems, developers often had to implement "keep rules" for their Data Transfer Objects (DTOs), essentially telling the obfuscator to leave certain type names untouched so that serialization wouldn’t break. This often meant surrendering the very parts of the hierarchy that were most in need of protection.

With System.Text.Json, these exclusions become unnecessary. Because the hierarchy’s registration relies on tokens and literals, a modern obfuscator like Nebula.NET can rename the entire polymorphic hierarchy without any special configuration. The types can be renamed, their control flows flattened, and their strings encrypted, all while maintaining a stable serialization contract.

Furthermore, the use of .NET Source Generators adds another layer of robustness. By using a [JsonSerializable] context, the serialization logic—including the discriminators and property names—is baked into the generated code at compile-time. This happens before the obfuscator even runs. The generated constants for "circle" and "rect" are frozen, ensuring that no amount of post-processing can alter the output format.

Verification and Cross-Build Stability

The ultimate test of any serialization strategy is its performance in a production-like environment. For organizations managing persisted data, it is not enough to prove that a single build can round-trip its own data. The real requirement is cross-build stability: the ability to serialize data with one version of the application and deserialize it with a subsequent, obfuscated version.

Industry best practices now suggest incorporating specific integration tests that run against the "protected" or obfuscated artifacts. By capturing a JSON string from an older build and attempting to deserialize it using the current obfuscated assembly, developers can catch silent, data-corrupting regressions before they reach production. If the test successfully yields the correct concrete type after a rename, the developer can be confident that the document remains safe.

The shift toward explicit discriminators represents a broader principle in software architecture: type identity on the wire should be a value owned by the developer, never a byproduct of the compiler’s internal naming scheme. By adhering to this standard, .NET developers can leverage the full power of obfuscation and modern serialization without the fear of rendering their historical archives unreadable. As the ecosystem continues to evolve, the reliance on CLR-bound identities is likely to become a relic of the past, replaced by the more intentional and secure patterns found in modern .NET frameworks.