Development Playbook

Move from Newtonsoft.Json to System.Text.Json without changing what your API accepts

A parity test grades the agent's migration against the old serialiser, and every difference needs a written reason. About 15 minutes to set up, C# on .NET 10.

Two overlapping circles, one filled with teal dots and one with gold hatching, glowing where they overlap and slightly notched where the outlines disagree

Somebody swaps JsonConvert for System.Text.Json across a service, the build is green, the existing tests are green, and a week later a partner’s integration starts returning 400s. Their client has always sent "status": "shipped" in lower case. Or a trailing comma. Or "total": "12.5" in quotes. Newtonsoft.Json accepted all of it without a word, and nobody ever wrote that down, so nothing in the test suite knew.

An agent will happily do this migration, and that’s the problem: it makes the code compile and the tests it can see pass. What it can’t see is the set of payloads your callers send today. This Playbook builds a small parity test that turns the old serialiser into the judge. The agent changes the options until the new serialiser behaves like the old one on a corpus of payloads, and every difference that survives needs a written reason from a human.

It works with any agent that can read files and run dotnet test. The technique, the prompt and the check don’t depend on one tool.

What you’re building

Four small files in a test project:

  • A corpus of JSON payloads, one per behaviour you want to pin, each with an id.
  • The legacy settings and the candidate options, side by side.
  • A theory that reads every payload with both serialisers and compares the resulting objects, plus one test that compares what each serialiser writes.
  • An approvals file: a dictionary from payload id to the reason a difference is accepted.

The agent edits the candidate options and nothing else. The corpus, the test and the approvals are yours.

Start with the model. This is the order DTO the examples use, with the usual mix of things that behave differently between the two libraries: an enum, a decimal, a DateTime, a dictionary, a private setter and a public field.

namespace Orders;

public enum Status { Pending, Shipped, Cancelled }

public class Line
{
    public string Sku { get; set; } = "";
    public int Qty { get; set; }
}

public class Order
{
    public Guid Id { get; set; }
    public string? CustomerName { get; set; }
    public Status Status { get; set; }
    public decimal Total { get; set; }
    public DateTime PlacedAt { get; set; }
    public DateTimeOffset? ShippedAt { get; set; }
    public List<Line> Lines { get; set; } = new();
    public Dictionary<string, int> Counts { get; set; } = new();
    public string Note { get; private set; } = "none";
    public int Priority = 3;
    public long BigId { get; set; }
}

Pin down what production does today

The legacy settings are whatever your service really uses. Copy them, don’t tidy them. The example has camelCase names and NullValueHandling.Ignore, which is common enough to matter, as you’ll see.

The candidate starts as the thing an agent writes first: the Web preset and a matching null-handling option. Microsoft’s reference says JsonSerializerDefaults.Web implies case-insensitive property names, camelCase and quoted numbers allowed, so it looks like a faithful port.

using System.Text.Json;
using System.Text.Json.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Orders;

public static class Serialisers
{
    // What production does today. This is the oracle.
    public static readonly JsonSerializerSettings Legacy = new()
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver(),
        NullValueHandling = NullValueHandling.Ignore,
    };

    // The agent's first attempt.
    public static readonly JsonSerializerOptions Candidate = new(JsonSerializerDefaults.Web)
    {
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
    };
}

Newtonsoft and System.Text.Json share type names (JsonException, JsonSerializer, JsonConverter), so keep each library’s using in separate files where you can, and fully qualify the rest. The test project below does exactly that.

Build the corpus first

Each entry is a payload that one real behaviour depends on. Twenty-two cover this DTO: quoted numbers, enum names in any case, enum numbers, an undefined enum value, a numeric string for an enum, a private setter, a public field, an unknown member, a comment, a trailing comma, nulls in four places, date formats, a bad GUID, a duplicate member, dictionary keys that differ only by case, a long above 2^53 and an integral float into an int.

namespace Orders;

public static class Corpus
{
    public static readonly (string Id, string Json)[] Payloads =
    [
        ("quoted-number",       """{"total":"12.5"}"""),
        ("enum-name-any-case",  """{"status":"shipped"}"""),
        ("enum-number",         """{"status":1}"""),
        ("enum-undefined",      """{"status":7}"""),
        ("enum-numeric-string", """{"status":"1"}"""),
        ("private-setter",      """{"note":"hi"}"""),
        ("public-field",        """{"priority":9}"""),
        ("unknown-member",      """{"unknownField":1,"total":3}"""),
        ("comment",             "{\"total\":1, // c\n \"bigId\":1}"),
        ("trailing-comma",      """{"total":1,}"""),
        ("null-into-decimal",   """{"total":null}"""),
        ("null-into-datetime",  """{"placedAt":null}"""),
        ("null-list",           """{"lines":null}"""),
        ("null-dictionary",     """{"counts":null}"""),
        ("date-only",           """{"placedAt":"2026-11-26"}"""),
        ("date-offset",         """{"shippedAt":"2026-11-26T09:30:00+01:00"}"""),
        ("bad-guid",            """{"id":"not-a-guid"}"""),
        ("duplicate-member",    """{"total":1,"total":2}"""),
        ("case-clash-keys",     """{"counts":{"A":1,"a":2}}"""),
        ("big-long",            """{"bigId":9007199254740993}"""),
        ("float-into-int",      """{"lines":[{"qty":2.0}]}"""),
        ("empty-object",        "{}"),
    ];
}

Real payloads beat invented ones. If you can, sample a few hundred from request logs (scrubbed of anything personal) and add the ones that exercise a distinct shape. An agent is good at proposing entries from the DTO definitions, and you can ask for that, but read the list yourself. The corpus is the specification, and it only contains what somebody thought to ask.

The test that grades the agent

The theory reads each payload with both libraries and renders the resulting object through one neutral serialiser. That matters: comparing the objects, not the libraries’ own output, stops the comparison being about how each one formats numbers. A failure to parse becomes the single word REJECTED, because the exact exception types differ and nobody depends on them.

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;

namespace Orders;

public class ParityTests
{
    static readonly JsonSerializerSettings Neutral = new() { Formatting = Formatting.None };

    static string Render(Func<Order?> read)
    {
        try
        {
            var o = read();
            return JObject.FromObject(o!, Newtonsoft.Json.JsonSerializer.Create(Neutral))
                          .ToString(Formatting.None);
        }
        catch (Exception e) when (e is Newtonsoft.Json.JsonException
                                     || e is System.Text.Json.JsonException)
        {
            return "REJECTED";
        }
    }

    public static IEnumerable<object[]> Cases() =>
        Corpus.Payloads.Select(p => new object[] { p.Id, p.Json });

    [Theory, MemberData(nameof(Cases))]
    public void Reading_matches_legacy_unless_approved(string id, string payload)
    {
        var legacy = Render(() =>
            JsonConvert.DeserializeObject<Order>(payload, Serialisers.Legacy));
        var candidate = Render(() =>
            System.Text.Json.JsonSerializer.Deserialize<Order>(payload, Serialisers.Candidate));
        var approved = Approved.Reasons.TryGetValue(id, out var why);

        if (legacy == candidate)
        {
            Assert.False(approved,
                $"'{id}' is approved as a difference but both now agree. Remove the approval.");
            return;
        }
        Assert.True(approved,
            $"'{id}' differs.\n  legacy   : {legacy}\n  candidate: {candidate}");
        Assert.False(string.IsNullOrWhiteSpace(why));
    }

    [Fact]
    public void Writing_matches_legacy()
    {
        var order = new Order
        {
            Id = Guid.Parse("0f8fad5b-d9cb-469f-a165-70867728950e"),
            Status = Status.Shipped,
            Total = 10.50m,
            PlacedAt = new DateTime(2026, 11, 26, 7, 0, 0, DateTimeKind.Utc),
            ShippedAt = new DateTimeOffset(2026, 11, 27, 9, 30, 0, TimeSpan.FromHours(1)),
            Lines = { new Line { Sku = "A-1", Qty = 2 } },
            Counts = { ["Alpha"] = 1 },
            BigId = 9007199254740993,
        };
        var legacy = JObject.Parse(JsonConvert.SerializeObject(order, Serialisers.Legacy));
        var candidate = JObject.Parse(
            System.Text.Json.JsonSerializer.Serialize(order, Serialisers.Candidate));

        // JObject.DeepEquals ignores member order, which JSON consumers ignore too.
        Assert.True(JToken.DeepEquals(legacy, candidate),
            $"\n  legacy   : {legacy.ToString(Formatting.None)}\n  candidate: {candidate.ToString(Formatting.None)}");
    }
}

The approvals file starts empty. It’s the ledger the rest of the piece depends on.

namespace Orders;

public static class Approved
{
    // Differences a human accepted on purpose. Every entry needs a reason.
    public static readonly Dictionary<string, string> Reasons = new();
}

The test checks the ledger in both directions. A difference without an entry fails. An entry whose difference has disappeared also fails, so the ledger can’t fill up with reasons for things that no longer happen.

Run it against the naive migration

dotnet test

The first attempt, which looked faithful, fails on 10 of 23 tests:

Failed Orders.ParityTests.Reading_matches_legacy_unless_approved(id: "comment" ...)
Failed Orders.ParityTests.Reading_matches_legacy_unless_approved(id: "null-dictionary" ...)
Failed Orders.ParityTests.Reading_matches_legacy_unless_approved(id: "enum-numeric-string" ...)
Failed Orders.ParityTests.Reading_matches_legacy_unless_approved(id: "trailing-comma" ...)
Failed Orders.ParityTests.Reading_matches_legacy_unless_approved(id: "public-field" ...)
Failed Orders.ParityTests.Reading_matches_legacy_unless_approved(id: "enum-name-any-case" ...)
Failed Orders.ParityTests.Reading_matches_legacy_unless_approved(id: "null-into-decimal" ...)
Failed Orders.ParityTests.Reading_matches_legacy_unless_approved(id: "null-list" ...)
Failed Orders.ParityTests.Reading_matches_legacy_unless_approved(id: "null-into-datetime" ...)
Failed Orders.ParityTests.Writing_matches_legacy
Failed!  - Failed:    10, Passed:    13, Skipped:     0, Total:    23

Three of the passes are worth a second look, because they’re the ones a reviewer assumes will fail. quoted-number passes because the Web preset allows quoted numbers. enum-undefined passes because System.Text.Json also lets an out-of-range number through into an enum. unknown-member passes because both libraries ignore what they don’t recognise by default. If you had assumed the migration doc’s table was the whole story, you would have written fewer tests.

Let the agent iterate, with a fence around it

Here’s the prompt. It works in any coding agent, because it only asks for edits to one file and a test run.

Make Serialisers.Candidate pass `dotnet test` in the Parity.Tests project.

You may edit Serialisers.cs and add new converter files. Do not edit
Corpus.cs, ParityTests.cs or Approved.cs.

For each failing payload, change the candidate options or add a converter so
the object it produces matches the legacy result. If you can't match it, stop
and report: the payload id, both outcomes, why no option closes the gap, and
whether you think the difference is acceptable. Don't add anything to the
approvals file.

Then enforce the fence rather than trusting it. This runs after the agent finishes and fails if a protected file moved:

if git diff --name-only HEAD | grep -E 'Corpus.cs|ParityTests.cs|Approved.cs'; then
  echo "protected test files were edited" >&2
  exit 1
fi

Put it in CI as well. A test the agent can edit is a test the agent can pass by editing it.

What the agent has to find

Each round of fixes is a small option or a small converter. The first round covers the cheap ones.

public static readonly JsonSerializerOptions Candidate = new(JsonSerializerDefaults.Web)
{
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
    ReadCommentHandling = JsonCommentHandling.Skip,
    AllowTrailingCommas = true,
    IncludeFields = true,
    DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
    Converters = { new JsonStringEnumConverter() },
};

Comments and trailing commas are single options. IncludeFields brings back the public Priority field. DictionaryKeyPolicy fixes a quiet one: Newtonsoft’s camel-case resolver also lowercases dictionary keys, so Alpha went out as alpha, and a consumer looking up alpha would have started missing it.

The enum line is the instructive mistake. JsonStringEnumConverter reads names in any case, so the read failures go away. It also writes names. Run the tests again and the writing test fails:

Failed Orders.ParityTests.Writing_matches_legacy
  legacy   : {"priority":3,"id":"0f8fad5b-...","status":1,"total":10.5, ...
  candidate: {"id":"0f8fad5b-...","status":"Shipped","total":10.5, ...
Failed!  - Failed:     5, Passed:    18, Skipped:     0, Total:    23

Legacy wrote 1 and the candidate writes "Shipped". Every client that parsed the number is now broken, and no read-side test would have said so. This is why the parity test covers both directions. The fix is a converter that reads names in any case, numbers and numeric strings, and writes the number.

using System.Text.Json;
using System.Text.Json.Serialization;

namespace Orders;

public sealed class LegacyEnumConverterFactory : JsonConverterFactory
{
    public override bool CanConvert(Type t) => t.IsEnum;

    public override JsonConverter CreateConverter(Type t, JsonSerializerOptions o) =>
        (JsonConverter)Activator.CreateInstance(typeof(Conv<>).MakeGenericType(t))!;

    sealed class Conv<T> : JsonConverter<T> where T : struct, Enum
    {
        public override T Read(ref Utf8JsonReader r, Type t, JsonSerializerOptions o)
        {
            if (r.TokenType == JsonTokenType.Number && r.TryGetInt64(out var n))
                return (T)Enum.ToObject(typeof(T), n);
            if (r.TokenType == JsonTokenType.String
                && Enum.TryParse<T>(r.GetString(), true, out var v))
                return v;
            throw new JsonException($"Cannot read {typeof(T).Name}.");
        }

        public override void Write(Utf8JsonWriter w, T value, JsonSerializerOptions o) =>
            w.WriteNumberValue(Convert.ToInt64(value));
    }
}

Four failures remain, and they’re all about null. NullValueHandling.Ignore in the legacy settings doesn’t only skip nulls on write. In this corpus it also made Newtonsoft skip a null on read, leaving the property at its default. The two lines and counts cases keep an empty collection under legacy and become null under System.Text.Json, which is a NullReferenceException waiting in the first loop that touches them.

System.Text.Json has no option for that, but a contract modifier can do it. The custom-contracts page documents replacing JsonPropertyInfo.Set to change what happens on deserialisation, which is all this needs.

static void SkipNullOnRead(JsonTypeInfo info)
{
    foreach (var p in info.Properties)
    {
        if (p.Set is { } set)
            p.Set = (obj, value) => { if (value is not null) set(obj, value); };
    }
}

// in Candidate:
TypeInfoResolver = new DefaultJsonTypeInfoResolver { Modifiers = { SkipNullOnRead } },

That closes null-list and null-dictionary. It can’t close null-into-decimal or null-into-datetime. The parser throws when it meets a JSON null for a non-nullable value type. The run now reads:

Failed Orders.ParityTests.Reading_matches_legacy_unless_approved(id: "null-into-decimal" ...)
  legacy   : {"Id":"00000000-...","Status":0,"Total":0.0, ...}
  candidate: REJECTED
Failed Orders.ParityTests.Reading_matches_legacy_unless_approved(id: "null-into-datetime" ...)
  legacy   : {"Id":"00000000-...","Status":0,"Total":0.0, ...}
  candidate: REJECTED
Failed!  - Failed:     2, Passed:    21, Skipped:     0, Total:    23

This is the point where the agent should stop and report, as the prompt asks, because the remaining question isn’t technical. Clients that send "total": null used to get a silent zero. Now they’ll get a 400. Maybe that’s what you want, since a silent zero in a money field is a bug that has been hidden. Maybe a partner depends on it. You find out by asking, or by checking the request logs, and then you write the answer down.

Approve differences with reasons

public static readonly Dictionary<string, string> Reasons = new()
{
    ["null-into-decimal"] =
        "Clients sending null for a required number now get a 400 instead of a silent 0. Agreed with the mobile team.",
    ["null-into-datetime"] =
        "Same as null-into-decimal: a null date is a client bug we would rather see.",
};

Run it:

Passed!  - Failed:     0, Passed:    23, Skipped:     0, Total:    23

Now the ledger is a record of the decision, in the repository, next to the code, with a test that will notice if the decision stops being true. To see the reverse check work, add an approval for a payload that already matches, such as quoted-number:

Failed Orders.ParityTests.Reading_matches_legacy_unless_approved(id: "quoted-number" ...)
Failed!  - Failed:     1, Passed:    22, Skipped:     0, Total:    23

Remove the stray line and it’s green again. The message says what to do: remove the approval.

Make it yours

If the service is ASP.NET Core with AddNewtonsoftJson, the same candidate options plug into ConfigureHttpJsonOptions (minimal APIs) or AddJsonOptions (controllers). Microsoft’s migration page notes that ASP.NET Core already sets camel-casing and case-insensitive matching when it uses System.Text.Json, so the test should build its candidate from the options the app really uses, not a copy that drifts. Resolve them from the service provider in a WebApplicationFactory test if you can.

For a larger codebase, add one theory per DTO that crosses a boundary, and share the legacy and candidate settings. The cost is the corpus, not the harness. A hundred payloads sampled from real traffic are a better regression suite for this migration than a thousand lines of unit tests that never saw a trailing comma.

If you use JObject or JToken anywhere, those are a separate migration (to JsonNode), and this harness doesn’t cover them. Same for polymorphic types that rely on $type, custom JsonConverter classes from Newtonsoft, and anything that depends on culture. Add payloads for them before you touch them, and expect the agent to need real help.

What goes wrong

The corpus only holds what someone thought of. A passing run means the library behaves the same on 22 payloads, not on all of them. Date handling is where this shows first. Newtonsoft’s DateTimeZoneHandling and DateFormatString have no direct counterpart, and the migration page lists them as unsupported. If your API depends on a format other than ISO 8601, put that format in the corpus in both directions.

Comparing the object state hides the order of members, whitespace and number formatting on the wire. Consumers that parse JSON don’t care. A consumer that signs the raw body, or diffs it as text, does, so add an exact-string test for that endpoint specifically.

Performance isn’t measured here. The migration is often motivated by speed, but a parity test won’t tell you whether you got any, and a custom enum converter in a hot path has a cost of its own. Benchmark separately.

And don’t bother with all of this if the API is internal, has one client you control, and you can change both sides in one deployment. A single pull request that updates the client and the server together needs a round-trip test, not a ledger.

The first 15 minutes

Create an xUnit project next to the one that owns the DTOs and reference both Newtonsoft.Json and the project under test. Copy the legacy settings from your startup code into Serialisers.Legacy. Write ten payloads from your request logs and the list above, leave the candidate as the bare Web preset, and run dotnet test. The failures are the migration plan.