# Obfuscating a JSON source-generated context


A `[JsonSerializable]` context is the serializer you reach for when you are about to obfuscate. The reflection-based path reads your live property names at runtime, so renaming `CustomerRef` to `a` turns your JSON into `{"a":…}`; the source-generated path resolves everything at compile time and reaches your members through typed delegates, so the rename is invisible on the wire. That much is well known.

What is less obvious is *how* the generated context stays intact — and where it does not. The generator writes the serialization contract down in **two kinds of thing**: tokens that the renamer follows, and literals that it leaves exactly where they are. A source-generated `JsonSerializerContext` is rename-safe precisely when those two halves stay in step, and it desyncs the moment a code path sidesteps the context. So the question worth answering concretely is: what does the generator actually emit, which parts move under renaming and which do not, and how do you prove the halves still line up after Nebula runs?

## What the generator emits

Start with a DTO carrying one explicit wire name and a context for it:

```csharp
public sealed class Order
{
    [JsonPropertyName("customer_ref")] public string CustomerRef { get; set; } = "";
    public decimal Total { get; set; }
}

[JsonSerializable(typeof(Order))]
internal partial class AppJsonContext : JsonSerializerContext { }
```

Turn on `<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>` and read what the generator produced. Two pieces matter. First, the context resolves a type to its `JsonTypeInfo` **by identity**:

```csharp
public override JsonTypeInfo? GetTypeInfo(Type type)
{
    if (type == typeof(global::Order))   return this.Order;
    if (type == typeof(string))          return this.String;
    if (type == typeof(decimal))         return this.Decimal;
    return null;
}
```

There is no string anywhere in that method. `typeof(global::Order)` compiles to an `ldtoken` of the type's metadata handle, and `type ==` is a reference comparison against the runtime `Type` the serializer already holds. When the renamer turns `Order` into `a`, it rewrites the `ldtoken` and the `this.Order` property reference together — `GetTypeInfo(typeof(a))` still returns the right metadata. This is the whole reason the context survives: resolution is token-based end to end.

Second, the per-property metadata. In the default metadata mode the generator emits an initializer like this (trimmed):

```csharp
private static JsonPropertyInfo[] OrderPropInit(JsonSerializerOptions options)
{
    var properties = new JsonPropertyInfo[2];

    var info0 = new JsonPropertyInfoValues<string>
    {
        IsProperty       = true,
        DeclaringType    = typeof(global::Order),
        Getter           = static obj => ((global::Order)obj).CustomerRef,
        Setter           = static (obj, value) => ((global::Order)obj).CustomerRef = value!,
        JsonPropertyName = "customer_ref",   // from [JsonPropertyName], captured as a literal
        PropertyName     = "CustomerRef",     // the CLR name, also captured
    };
    properties[0] = JsonMetadataServices.CreatePropertyInfo<string>(options, info0);
    // ... Total ...
    return properties;
}
```

The getter and setter are **lambdas that touch the member directly** — in IL, `ldftn` on a compiler-generated method whose body is `callvirt Order::get_CustomerRef()`. The wire name is a **`ldstr "customer_ref"`**. After Nebula renames `Order` to `a` and `CustomerRef` to `b`, the lambda body becomes `callvirt a::get_b()`, rewritten by token like every call site, while the `ldstr` still reads `"customer_ref"`. Serialize an order and you get `{"customer_ref":"…","total":…}` exactly as before.

<figure class="my-8"><svg viewBox="0 0 720 300" role="img" aria-label="Diagram contrasting the reflection serializer and a source-generated JsonSerializerContext after renaming. The reflection path resolves the type and property by reading the live member name from metadata at runtime, so after CustomerRef is renamed to b the JSON key becomes b and the contract breaks. The generated context resolves the type by typeof identity through GetTypeInfo, reaches the property through a getter delegate rewritten by token, and emits the wire name from a string literal captured at generation time, so after renaming the JSON key stays customer_ref and the contract holds." style="width:100%;height:auto"><defs><style>.ti{font:600 13px system-ui;fill:#6366f1}.h{font:600 11px system-ui;fill:#0f172a}.x{font:10px system-ui;fill:#64748b}.mono{font:10px ui-monospace,Consolas,monospace;fill:#334155}.ref{fill:#eef2ff;stroke:#a5b4fc}.bad{fill:#fee2e2;stroke:#f87171}.ok{fill:#d1fae5;stroke:#34d399}.lit{fill:#fef3c7;stroke:#fbbf24}.ar{stroke:#64748b;stroke-width:1.3;fill:none;marker-end:url(#ah)}</style><marker id="ah" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto"><path d="M0,0 L8,4 L0,8 z" fill="#64748b"/></marker></defs><text class="ti" x="12" y="20">Reflection resolver — binds by live name</text><rect class="ref" x="12" y="32" width="300" height="46" rx="5"/><text class="mono" x="22" y="52">GetProperty / walk metadata</text><text class="x" x="22" y="70">reads p.Name at runtime</text><rect class="ref" x="12" y="92" width="300" height="34" rx="5"/><text class="mono" x="22" y="114">CustomerRef renamed to b</text><rect class="bad" x="12" y="140" width="300" height="34" rx="5"/><text class="h" x="22" y="162">JSON key = "b"  → contract breaks</text><path class="ar" d="M162,78 L162,92"/><path class="ar" d="M162,126 L162,140"/><text class="ti" x="372" y="20">Generated context — type identity + literal</text><rect class="ref" x="372" y="32" width="336" height="60" rx="5"/><text class="mono" x="382" y="52">GetTypeInfo: type == typeof(Order)</text><text class="mono" x="382" y="68">Getter = o =&gt; o.CustomerRef   (token)</text><text class="mono" x="382" y="84">JsonPropertyName = "customer_ref"</text><rect class="ref" x="372" y="106" width="336" height="30" rx="5"/><text class="mono" x="382" y="126">Order→a, CustomerRef→b  (tokens rewritten)</text><rect class="lit" x="372" y="150" width="160" height="30" rx="5"/><text class="x" x="382" y="170">literal unchanged</text><rect class="ok" x="542" y="150" width="166" height="30" rx="5"/><text class="h" x="552" y="170">key = "customer_ref"</text><path class="ar" d="M540,92 L540,106"/><path class="ar" d="M540,136 L540,150"/><text class="x" x="12" y="214">The renamer rewrites typeof tokens and delegate bodies consistently; it never touches a string literal.</text><text class="x" x="12" y="232">The generated context captures the wire name as a literal at generation time, so renaming the member cannot move it.</text><text class="x" x="12" y="250">Reflection has no token joining the JSON key to the member — the join is the name, and the name moved.</text></svg><figcaption class="text-sm text-muted mt-2">The reflection resolver binds the wire key to the live member name; the generated context binds the type by <code>typeof</code> identity and the wire name to a captured literal — both rename-safe.</figcaption></figure>

In the **fast-path** serialization mode the shape is the same, just hand-written: a pre-encoded `private static readonly JsonEncodedText PropName_customer_ref = JsonEncodedText.Encode("customer_ref");` and a `writer.WriteString(PropName_customer_ref, value.CustomerRef)`. Literal plus direct member access, again. Whichever mode the generator picked, the rule is the inverse of the reflection rule: **the member is safe to rename; the literal is what you reason about.**

## The constructor is bound positionally

An immutable DTO adds a wrinkle the reflection serializer handles by *parameter name*. The generator handles it differently — and better. Give `Order` a parameterized constructor and the generated object metadata carries a positional creator plus parameter info:

```csharp
objectInfo.CreateObjectWithArgs =
    static args => new global::Order((string)args[0]!, (decimal)args[1]!);

// parameter metadata the serializer matches JSON properties against:
new JsonParameterInfoValues { Name = "customerRef", Position = 0, ParameterType = typeof(string) };
new JsonParameterInfoValues { Name = "total",       Position = 1, ParameterType = typeof(decimal) };
```

The object is constructed through a delegate that calls the constructor **positionally** — `args[0]`, `args[1]` — so the constructor call is a token and renaming the constructor changes nothing. The `Name = "customerRef"` literal is what pairs a deserialized property to its slot, and it was captured at generation time, so renaming the constructor parameters to `p0, p1` cannot desync it. This is a real improvement over the reflection path, where that pairing is read from live parameter-name metadata and a parameter renamer can break it. With the generated context, the parameter names are frozen into literals before Nebula runs.

## Where the context and the wire still desync

The generated context is safe, but only for traffic that actually goes *through* it. Three paths leave it:

**A reflection fallback.** `JsonSerializer.Serialize(order)` with no context argument, or a resolver chain that ends in `DefaultJsonTypeInfoResolver` for a type the context does not cover, resolves names from live metadata — and emits the renamed names. You do not want to find that in the obfuscated build. Close the door at the project level so it throws in development:

```xml
<PropertyGroup>
  <JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
</PropertyGroup>
```

**A context resolved by name.** `Type.GetType("AppJsonContext")` or any reflective construction of the context is a string dependency the renamer invalidates. Reach the context the generated way — `AppJsonContext.Default` and its per-type `AppJsonContext.Default.Order` — which are token references that rename with your call sites.

**A missing `[JsonPropertyName]`.** The generator always captures *a* wire name, but when you omit the attribute that literal is whatever the property was called in source. Two costs follow: a later source rename silently changes the wire (the captured literal moves with it at the next build), and the original member name sits in the assembly as a readable `ldstr`. Attribute the names that are contracts, and turn on `encryptStrings` so the captured literals — wire names and the `PropertyName` copies — are encrypted at rest and decrypted at runtime. The JSON is unaffected; the map of original names is gone from the file.

## The rules for the context type

Do **not** exclude the `JsonSerializerContext`-derived type by reflex. The context, its `Default` property and the per-type `JsonTypeInfo<T>` properties are reached by token from your own code, so the renamer rewrites every reference consistently and nothing breaks — excluding it only hands an attacker a clean, named map of your serialized model. Preserve it in exactly two situations: the context is **public API** another assembly consumes across the obfuscation boundary (use `preservePublicApi`, or `exclude` that one type), or it is **resolved by name** somewhere (remove the reflective lookup instead). In both cases the DTOs behind it still rename freely.

## Prove the halves line up

The assertion that matters runs against the **obfuscated** artifact, because the whole failure mode only appears after Nebula renames. A round-trip plus a resolver check catches every desync above:

```csharp
[Fact]
public void Protected_build_round_trips_through_the_generated_context()
{
    var order = new Order("ACME-7", 42.50m);

    var json = JsonSerializer.Serialize(order, AppJsonContext.Default.Order);
    Assert.Contains("\"customer_ref\":\"ACME-7\"", json);  // the contract, literally
    Assert.DoesNotContain("\"b\":", json);                 // no renamed member leaked

    var back = JsonSerializer.Deserialize(json, AppJsonContext.Default.Order)!;
    Assert.Equal("ACME-7", back.CustomerRef);              // ctor matched positionally

    // the context still resolves the (renamed) type by identity
    Assert.NotNull(AppJsonContext.Default.GetTypeInfo(typeof(Order)));
}
```

Wire that against the post-obfuscation build in CI and "serialization broke" becomes a red test instead of a customer email. The principle generalizes: a source-generated context is the easiest serializer in your assembly to obfuscate because it resolves by token and carries its contract as literals — your job is only to keep every serialization path *inside* it, and to encrypt the names it wrote down.

For the reflection-side version of this problem, see [obfuscating System.Text.Json types without breaking JSON](https://delta1labs.com/blog/obfuscate-system-text-json-jsonpropertyname-contract/); for the broader generator picture, [obfuscating source-generated code safely](https://delta1labs.com/blog/obfuscate-source-generated-code-stj-generatedregex-loggermessage/). [Nebula.NET](https://delta1labs.com/products/nebula/) renames aggressively by design, and the rules above are how the one name that has to stay does. [Download it free](https://delta1labs.com/download?product=nebula) and run your round-trip against the protected build.

