C#

Obfuscating a JSON source-generated context

DEV Community: #dotnet Zero Heartbeat
C#

A walkthrough of how System.Text.Json's source-generated context behaves under renaming: why token-based type lookup and captured wire-name literals survive obfuscation, where reflection paths still leak renamed members, and how to test the protected build.

Key points

  • Generated GetTypeInfo() compares typeof tokens, so renamed types still resolve to the right JsonTypeInfo.
  • Property metadata captures the wire name as a string literal while getters and setters call the possibly renamed members.
  • Fast-path mode stores names in pre-encoded JsonEncodedText fields, so the same literal rule applies.
  • Constructors bind positionally through CreateObjectWithArgs and args[0], so renamed parameters cannot break deserialization.
  • Set <JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault> so any reflection fallback throws early.
  • Round-trip and GetTypeInfo assertions have to run against the obfuscated artifact, where the desync appears.

Why it matters

Obfuscation matters mostly to teams shipping client-side .NET: desktop apps, licensing-protected libraries, on-premise installs where the IL sits in the customer's hands. If those assemblies serialize JSON, the source-generated context is the piece to standardize on, and the checklist is short: no bare JsonSerializer.Serialize calls, no Type.GetType lookups of the context, [JsonPropertyName] on every name that is a contract.

The test is what teams skip. Serialization breaks only after renaming, so the assertion runs in CI against the protected artifact, not the debug build. encryptStrings hides literals at rest, not at runtime, and obfuscation raises the effort for a reader; it does not make the JSON contract secret.

Real-world use

  • A desktop app whose DTOs are renamed but whose JSON must stay compatible with saved files and external clients.
  • An immutable DTO deserialized through a parameterized constructor whose parameter names change under renaming.
  • A JsonSerializerContext exposed as public API and consumed by another assembly across the obfuscation boundary.
  • A CI pipeline that round-trips JSON against the protected build before release.

This summary was generated by the agent from the original post on DEV Community: #dotnet. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message