Skip to main content

Test JSON and Reflection Contracts Before Renaming .NET Code

Updated 7 min readMarkdown

A .NET application can compile successfully while depending on names that the compiler never treats as a public interface. A JSON field read by another service, a plug-in entry point found with a string, or a property reached through a binding expression can all become part of a contract.

Disclosure: this article was drafted with AI assistance and checked against the linked primary sources. It is prepared for ProofCloak, an open-beta .NET code protection project. The standalone sample was executed locally; it is not evidence of an actual obfuscation or production run.

Changing those names without changing their consumers can break a release. This matters when refactoring, introducing code protection, replacing a serializer, or changing a build configuration. The useful question is precise: which observable behavior must remain stable, and does the candidate artifact preserve it?

This article builds a small executable check for two boundaries: JSON property names and a reflection-discovered method. The example uses .NET 10 and System.Text.Json. It deliberately simulates source-level renaming. It does not run an obfuscator, measure resistance to reverse engineering, or establish that a particular protection tool supports a given application.

Begin with an external contract

Suppose an integration expects the following payload:

{"invoice_id":"INV-42","total_cents":1250}

The contract includes the property names, their kinds, and their meaning. Whether the implementation calls its CLR property Id, InvoiceIdentifier, or A is a separate decision.

System.Text.Json allows an explicit serialized name through JsonPropertyName. Microsoft's documentation explains that the attribute applies to serialization and deserialization and takes precedence over a naming policy. It does not, however, change how parameterized constructor parameters are matched. This example uses mutable properties to keep constructor matching outside its scope.

public sealed class Invoice
{
    [JsonPropertyName("invoice_id")]
    public string Id { get; set; } = "";

    [JsonPropertyName("total_cents")]
    public int TotalCents { get; set; }
}

An internal rename simulation can preserve those explicit external names:

public sealed class RenamedInvoice
{
    [JsonPropertyName("invoice_id")]
    public string A { get; set; } = "";

    [JsonPropertyName("total_cents")]
    public int B { get; set; }
}

Both models should emit the expected wire contract. A third model, with properties A and B but no attributes, emits a different shape under the default options. That third case gives the test a useful negative control.

The explicit names are still visible to a consumer inspecting the application. They are compatibility decisions, not a way to hide an API schema or a secret. Do not put private credentials in an attribute, a DTO, or any other client-side location on the assumption that renaming will protect them.

Make serializer metadata explicit

The complete sample uses a generated serializer context:

[JsonSerializable(typeof(Invoice))]
[JsonSerializable(typeof(RenamedInvoice))]
[JsonSerializable(typeof(UnstableInvoice))]
internal partial class InvoiceJson : JsonSerializerContext { }

It calls the overload that receives generated type information:

string json = JsonSerializer.Serialize(
    new Invoice { Id = "INV-42", TotalCents = 1250 },
    InvoiceJson.Default.Invoice);

The project sets JsonSerializerIsReflectionEnabledByDefault to false. An accidental return to an unconfigured reflection-based serializer path can then fail visibly. Microsoft's source-generation guide documents this switch and the context-based overloads.

This is not an application-wide compatibility guarantee. A different serializer, polymorphic payload, custom converter, or dynamically selected type introduces additional contracts. A transformation tool also has its own handling of metadata and generated code. Verify that handling on the actual output instead of assuming this source-level example proves it.

Assert what the consumer sees

A round trip through one implementation is insufficient by itself. If both serialization and deserialization move to the same wrong names, they can agree with each other while breaking an older client.

The sample therefore inspects the emitted document directly:

static bool HasExpectedWireContract(string json)
{
    using JsonDocument document = JsonDocument.Parse(json);
    JsonElement root = document.RootElement;
    return root.ValueKind == JsonValueKind.Object
        && root.EnumerateObject().Count() == 2
        && root.TryGetProperty("invoice_id", out JsonElement id)
        && id.ValueKind == JsonValueKind.String
        && id.GetString() == "INV-42"
        && root.TryGetProperty("total_cents", out JsonElement total)
        && total.ValueKind == JsonValueKind.Number
        && total.TryGetInt32(out int amount)
        && amount == 1250;
}

The check ignores property ordering and whitespace. Those are not requirements of this example. It rejects extra properties because this particular fixture describes an exact two-field payload. In an integration that permits additive fields, remove that restriction deliberately and document the compatibility rule. Strictness should express the real consumer contract, not an arbitrary snapshot.

Real tests should also cover representative persisted data, nullability, missing fields, enum representations, and version transitions. Successful serialization alone says little about whether a previously saved document can still be read correctly.

Treat string-based discovery as a separate boundary

Now consider a loader that expects a public parameterless method named CreateReport:

public sealed class ReportPlugin
{
    public string CreateReport() => "report-ok";
}

The consumer performs the lookup and checks the result:

MethodInfo? entry = plugin.GetMethod("CreateReport", Type.EmptyTypes);
bool reflectionPass = entry is not null
    && entry.ReturnType == typeof(string)
    && entry.Invoke(Activator.CreateInstance(plugin), null) is string result
    && result == "report-ok";

The negative fixture exposes the same behavior through a method named A. The original string lookup fails. Correct code still exists, but the discovery contract has changed.

For code you control, a shared interface or another explicit registration mechanism may reduce dependence on names. For an existing external plug-in protocol, changing the consumer may be impossible. Preserve the required entry point using a mechanism supported by your tooling, and keep a test that exercises the loader. A preservation setting without a behavioral test is an assumption that can become stale.

Trimming and obfuscation are different operations. Microsoft's trimming documentation identifies reflection and dynamic loading as areas needing special attention; that is useful context, not evidence that a trimming annotation configures an obfuscator. Do not interchange the tools' configuration contracts.

Run both the passing and failing paths

The companion project has no third-party package dependencies. From its directory:

dotnet publish -c Release -o publish
dotnet publish/ContractChecks.dll
dotnet publish/ContractChecks.dll --break-json
dotnet publish/ContractChecks.dll --break-reflection

The normal invocation must exit with code 0. Each negative invocation must exit with code 1. The flags select deliberately incompatible fixtures; they do not invoke code protection or modify a published assembly.

This distinction matters in a release pipeline. A test process that prints FAIL but exits successfully can still produce a green job. Conversely, an expected failing fixture must not be reported as a failed production release. The harness should record the command, expected outcome, actual exit code, and relevant output for each case.

After any transformation, repeat the real contract tests against the candidate assemblies with the actual consumer. A self-check contained inside a rewritten application can move with the implementation. Keep independent fixtures where practical, and exercise the installed package as well as the build directory.

What this gives you

These checks turn two hidden dependencies into explicit release requirements. They do not prove that every reflection path is covered, that a transformed application is secure, or that an application is compatible across all frameworks and platforms.

Start with the contracts your customers depend on. Give each one a representative fixture, a useful failure signal, and a known artifact to run against. When a change breaks one, the failure points to a concrete boundary rather than a vague report that the protected build no longer works.

References and disclosure

Affiliation: this article is prepared for the ProofCloak account, which develops an open-beta .NET code protection platform. The example is independent of its service and makes no claim about a service-side protection run.

Preparation disclosure: AI assisted with drafting and code preparation. The sample was executed locally; the accompanying verification record distinguishes ordinary publish checks from actual obfuscation or production testing.

Companion source

Download the complete standalone sample source (ZIP). The archive contains the project, program, PowerShell release gate, and README; no customer files or service credentials.

About the author

  • Building ProofCloak, an open-beta .NET code protection platform. Engineering notes on compatibility testing, reflection and serialization contracts, and verifying release artifacts. https://proofcloak.com

No comments yet. Be the first to comment.