الانتقال إلى المحتوى
.NETASP.NET Core· 6 دقائق للقراءة

Moving From Newtonsoft.Json to System.Text.Json: The Defaults That Change Your API

System.Text.Json is strict where Newtonsoft guesses, writes the declared type, and escapes non-ASCII text in your own calls. The defaults that silently change requests, responses and stored JSON.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

A team removes AddNewtonsoftJson() during a .NET 10 upgrade. The build is green and the endpoint tests, which check status codes, all pass. A week later, the mobile team reports two bugs: order responses no longer include cardLast4, and creating an order with "status": "Paid" now fails with 400. Then someone opens the outbox table and finds new rows with PascalCase keys and customer names stored as منى. None of it is in the diff. All of it comes from defaults.

The common misconception

The belief: System.Text.Json is a drop-in replacement for Newtonsoft.Json. Same job, same API shape, Serialize and Deserialize, so the same objects produce the same JSON.

There's a lot behind that belief. For simple DTOs, the output really is identical. ASP.NET Core already hides the most visible differences: it configures camelCase names, case-insensitive matching and numbers in quotes. And Microsoft's migration guide has a table where most Newtonsoft features get a check mark on the System.Text.Json side.

Read that table closely, though. Many check marks point to an attribute or a setting you have to add, not to a default. The guide states the design difference directly: System.Text.Json is strict by default and avoids guessing, for performance and security; Newtonsoft.Json is flexible by default.

What actually happens

Strict input where Newtonsoft guessed

Newtonsoft accepts JSON that isn't quite JSON, and values that aren't quite the right type. System.Text.Json follows RFC 8259 and the declared types exactly. In a test with ASP.NET Core's web settings, each of these worked with Newtonsoft and threw a JsonException with System.Text.Json, which a minimal API endpoint turns into a 400:

  • an enum sent as a name, "status": "Paid";
  • a comment or a trailing comma in the body;
  • a number sent for a string property, "customer": 42.

The declared type decides what's written

Newtonsoft serializes the object it finds at runtime. System.Text.Json serializes the type the property is declared as. Order.Payment is declared as Payment, so a CardPayment stored there loses CardLast4 in the output. There's no exception and no warning. is opt-in, on the base type, with [JsonDerivedType]. Without a type discriminator, it writes the derived properties and adds nothing else, which matches the old output.

ASP.NET Core's settings aren't JsonSerializer's settings

When ASP.NET Core reads a request or writes a response, it uses the web defaults: camelCase, case-insensitive names, numbers allowed in quotes. In a test, a minimal API response also wrote an Arabic customer name as-is. Your own JsonSerializer.Serialize(order) call uses none of that. It writes PascalCase keys, and its default encoder escapes every non-ASCII character, so the same name became منى. JsonSerializerOptions.Web fixes the naming but still escapes. Reading has the same split: with default options, {"id":5} deserialized to an Order with Id = 0, silently, because matching is case-sensitive.

object now means JsonElement

Anything typed as object, such as a Dictionary<string, object> of metadata, receives a boxed JsonElement, for numbers and strings too. Newtonsoft returned a long, a string or a JObject, so code that casts (long)meta["count"] now throws InvalidCastException. Read the value with GetInt64(), or give the property a real type.

Loops still throw, and "ignore" means null

Both libraries throw on a reference loop, such as an EF Core entity with a parent and a list of children. Teams that set ReferenceLoopHandling.Ignore in Newtonsoft usually switch to ReferenceHandler.IgnoreCycles, and that's close but not identical: Newtonsoft leaves the looping property out, while System.Text.Json writes it as null. Clients that check whether a property exists see a different payload.

The orders API, configured on purpose

Both versions use the same Order record, with an OrderStatus enum and a Payment property:

C# Program.cs
using System.Text.Json;var builder = WebApplication.CreateBuilder(args);var app = builder.Build();// Response: no cardLast4, because the property is declared as Paymentapp.MapGet("/orders/{id:int}", (int id) => new Order(id, "Mona",    OrderStatus.Paid, new CardPayment { Amount = 12.5m, CardLast4 = "4242" }));// Body with "status": "Paid" gets a 400: enum names aren't read by defaultapp.MapPost("/orders", (Order order) => TypedResults.Ok(order.Status));app.Run();// Own calls skip ASP.NET Core's settings: PascalCase, non-ASCII escapedstatic string ToOutbox(Order order) => JsonSerializer.Serialize(order);public class Payment { public decimal Amount { get; set; } }public class CardPayment : Payment { public string? CardLast4 { get; set; } }

Tested on .NET 10: with these changes, the response includes cardLast4 with no $type field, "status": "Paid" is accepted, and the outbox JSON has camelCase keys and readable Arabic, while <, > and & are still escaped. Controllers configure the same options through AddControllers().AddJsonOptions(...) instead of ConfigureHttpJsonOptions.

Newtonsoft vs System.Text.Json defaults

SituationNewtonsoft.JsonSystem.Text.Json
Enum sent as a nameAcceptedJsonException, a 400 in ASP.NET Core
Comments, trailing commas, a number for a stringAcceptedJsonException
Property declared as a base typeRuntime type's propertiesDeclared type's properties only
Non-ASCII text in your own callsWritten as-isEscaped as \uXXXX
Value deserialized into objectlong, string, JObject...JsonElement
Reference loop with "ignore"Property left outProperty written as null

How to apply it in your project

  1. Snapshot the contract before switchingSave the JSON of representative requests and responses while Newtonsoft still runs, then compare after the switch. Status-code tests won't catch a missing property.
  2. Search for the risky shapesLook for properties typed as base classes or interfaces, object and Dictionary<string, object>, enums that clients send, public fields and private setters, and any ReferenceLoopHandling setting.
  3. Configure the HTTP options in one placeSet converters, encoders and any leniency, such as AllowTrailingCommas or ReadCommentHandling, in ConfigureHttpJsonOptions or AddJsonOptions, and only the ones your clients actually need.
  4. Route every manual call through shared optionsReplace bare JsonSerializer.Serialize and Deserialize calls for caches, queues and outboxes with one shared options instance, so stored JSON matches what the API sends.

Key takeaways

  • System.Text.Json is strict by design: enum names, comments, trailing commas and wrongly typed values fail instead of being guessed.
  • It writes the declared type's properties; derived properties need [JsonDerivedType] on the base type.
  • ASP.NET Core's web settings apply only to HTTP; your own calls default to PascalCase, case-sensitive reads and escaped non-ASCII text.
  • Treat the switch as a contract change: snapshot the JSON, configure the differences on purpose, and share one options instance.

📚 المصادر

  1. Migrate from Newtonsoft.Json to System.Text.Json — Microsoft Learn
  2. How to instantiate JsonSerializerOptions with System.Text.Json — Microsoft Learn
  3. How to serialize properties of derived classes with System.Text.Json — Microsoft Learn
  4. How to preserve references in System.Text.Json — Microsoft Learn
  5. How to customize character encoding with System.Text.Json — Microsoft Learn

التعليقات (0)