
Moving From Newtonsoft.Json to System.Text.Json: The Defaults That Change Your API
- كاتب موثّق
- .NET 10
محتويات المقال
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
Serialize and Deserialize, so the same objects produce the same JSON.
What actually happens
Strict input where Newtonsoft guessed
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
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
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
object now means JsonElementobject, 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
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
Order record, with an OrderStatus enum and a Payment property:
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; } }using System.Text.Encodings.Web;using System.Text.Json;using System.Text.Json.Serialization;using System.Text.Unicode;var builder = WebApplication.CreateBuilder(args);builder.Services.ConfigureHttpJsonOptions(o => // minimal APIs o.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));var app = builder.Build();// ...the same two endpoints...app.Run();// One shared options instance: web naming, Arabic kept readablestatic string ToOutbox(Order order) => JsonSerializer.Serialize(order, Json.Web);[JsonDerivedType(typeof(CardPayment))] // write the runtime type's propertiespublic class Payment { public decimal Amount { get; set; } }public class CardPayment : Payment { public string? CardLast4 { get; set; } }static class Json{ static readonly JavaScriptEncoder Arabic = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.Arabic); public static readonly JsonSerializerOptions Web = new(JsonSerializerDefaults.Web) { Encoder = Arabic };}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
JsonException, a 400 in ASP.NET Core | ||
JsonException | ||
\uXXXX | ||
object | long, string, JObject... | JsonElement |
null |
How to apply it in your project
Snapshot the contract before switching Save 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. Search for the risky shapes Look for properties typed as base classes or interfaces, objectandDictionary<string, object>, enums that clients send, public fields and private setters, and anyReferenceLoopHandlingsetting.Configure the HTTP options in one place Set converters, encoders and any leniency, such as AllowTrailingCommasorReadCommentHandling, inConfigureHttpJsonOptionsorAddJsonOptions, and only the ones your clients actually need.Route every manual call through shared options Replace bare JsonSerializer.SerializeandDeserializecalls 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.
📚 المصادر
Migrate from Newtonsoft.Json to System.Text.Json — Microsoft Learn How to instantiate JsonSerializerOptions with System.Text.Json — Microsoft Learn How to serialize properties of derived classes with System.Text.Json — Microsoft Learn How to preserve references in System.Text.Json — Microsoft Learn How to customize character encoding with System.Text.Json — Microsoft Learn
التعليقات (0)