
لما تنقل من Newtonsoft.Json لـ System.Text.Json: الـ defaults اللي بتغيّر الـ API بتاعك
- كاتب موثّق
- .NET 10
محتويات المقال
AddNewtonsoftJson() وهو بيعمل upgrade لـ .NET 10. الـ build نجح، والـ endpoint tests، اللي بتشيّك على الـ status codes، عدّت كلها. بعد أسبوع، فريق الموبايل بلّغ عن مشكلتين: الـ responses بتاعة الأوردرات مبقاش فيها cardLast4، وعمل أوردر بـ "status": "Paid" بقى بيفشل بـ 400. وبعدين حد فتح جدول الـ outbox ولقى rows جديدة فيها keys بالـ PascalCase وأسامي العملاء متخزنة كده: منى. ولا حاجة من دول في الـ diff. كلهم جايين من الـ defaults.
الفكرة الغلط الشائعة
Serialize و Deserialize، فنفس الـ objects هتطلّع نفس الـ JSON.
اللي بيحصل فعلًا
input صارم في الحتت اللي Newtonsoft كان بيخمّن فيها
JsonException مع System.Text.Json، والـ minimal API endpoint بيحوّلها لـ 400:
enum متبعت كاسم، "status": "Paid"؛comment أو comma زيادة في آخر الـ body؛ رقم متبعت لـ property نوعها string، "customer": 42.
الـ declared type هو اللي بيحدد إيه اللي يتكتب
Order.Payment متعرّفة كـ Payment، فلو جواها CardPayment، الـ CardLast4 بيختفي من الـ output. لا exception ولا warning. والـ لازم تفعّله بنفسك على الـ base type بـ [JsonDerivedType]. ومن غير type discriminator، بيكتب الـ properties بتاعة الـ derived type ومش بيزوّد حاجة تانية، وده نفس الـ output القديم بالظبط.
الـ settings بتاعة ASP.NET Core مش هي settings الـ JsonSerializer
JsonSerializer.Serialize(order) اللي بتناديه بنفسك فمش بياخد أي حاجة من دول. بيكتب الـ keys بالـ PascalCase، والـ encoder الافتراضي بتاعه بيعمل escape لأي حرف مش ASCII، فنفس الاسم بقى منى. والـ JsonSerializerOptions.Web بيصلّح الأسماء بس لسه بيعمل escape. والقراية فيها نفس الانقسام: بالـ options الافتراضية، {"id":5} اتعمله deserialize لـ Order فيه Id = 0، من غير أي صوت، لأن الـ matching بيفرق بين الـ capital والـ small.
الـ object بقى معناه JsonElement
object بقى معناه JsonElementobject، زي Dictionary<string, object> فيها metadata، بتستلم JsonElement متعمله boxing، حتى للأرقام والـ strings. الـ Newtonsoft كان بيرجّع long أو string أو JObject، فالكود اللي بيعمل cast زي (long)meta["count"] بقى بيرمي InvalidCastException. اقرا القيمة بـ GetInt64()، أو ادّي الـ property نوع حقيقي.
الـ loops لسه بترمي exception، و"ignore" معناها null
ReferenceLoopHandling.Ignore في Newtonsoft غالبًا بتنقل لـ ReferenceHandler.IgnoreCycles، وده قريب بس مش نفس الحاجة: الـ Newtonsoft بيشيل الـ property اللي عاملة loop خالص، أما الـ System.Text.Json فبيكتبها null. والـ clients اللي بتشيّك الـ property موجودة ولا لأ هتشوف payload مختلف.
الـ orders API، متظبط وانت قاصد
Order، وفيه enum اسمه OrderStatus و property اسمها Payment:
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 من غير field اسمه $type، والـ "status": "Paid" بقى بيتقبل، والـ JSON بتاع الـ outbox بقى فيه keys بالـ camelCase وعربي مقري، ولسه الـ < و > و & بيتعملهم escape. والـ controllers بتظبط نفس الـ options عن طريق AddControllers().AddJsonOptions(...) بدل ConfigureHttpJsonOptions.
الـ defaults بتاعة Newtonsoft قصاد System.Text.Json
JsonException، يعني 400 في ASP.NET Core | ||
JsonException | ||
\uXXXX | ||
object | long أو string أو JObject... | JsonElement |
null |
تطبقها إزاي في مشروعك
خد snapshot للـ contract قبل ما تغيّر احفظ الـ JSON بتاع requests و responses تمثّل الـ API وانت لسه على Newtonsoft، وقارنه بعد التغيير. الـ tests اللي بتشيّك على الـ status code مش هتمسك property ناقصة. دوّر على الأشكال الخطر دوّر على properties نوعها base classes أو interfaces، و objectوDictionary<string, object>، والـ enums اللي الـ clients بتبعتها، والـ public fields والـ private setters، وأي setting اسمهReferenceLoopHandling.ظبط الـ HTTP options في مكان واحد حط الـ converters والـ encoders وأي تساهل، زي AllowTrailingCommasأوReadCommentHandling، فيConfigureHttpJsonOptionsأوAddJsonOptions، وبس اللي الـ clients بتاعتك محتاجاه فعلًا.عدّي كل call يدوي على options مشتركة بدّل أي JsonSerializer.SerializeوDeserializeمن غير options، في الـ caches والـ queues والـ outboxes، بـ options instance واحدة مشتركة، عشان الـ JSON المتخزن يطابق اللي الـ API بيبعته.
الخلاصة
الـ System.Text.Json صارم عن قصد: أسماء الـ enums، والـ comments، والـ commas الزيادة، والقيم اللي نوعها غلط بتفشل بدل ما يتخمّن معناها. بيكتب الـ properties بتاعة الـ declared type، والـ properties بتاعة الـ derived types محتاجة [JsonDerivedType]على الـ base type.الـ web settings بتاعة ASP.NET Core بتتطبق على الـ HTTP بس، والـ calls بتاعتك افتراضيًا PascalCase، وقراية بتفرق بين الـ capital والـ small، ونص مش ASCII متعمله escape. اتعامل مع التغيير ده على إنه تغيير في الـ contract: خد snapshot للـ JSON، وظبط الفروق وانت قاصد، واستخدم 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)