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.
