loading experience

.NET

System.Text.Json in .NET 10: stricter, safer JSON

Duplicate properties, strict options and reading from PipeReader: what is new in the .NET JSON serializer.

System.Text.Json in .NET 10: stricter, safer JSON

System.Text.Json is the JSON serializer built into .NET. In .NET 10 it adds options designed mainly for those who receive JSON from external sources and want to be strict.

With strict options, ambiguous documents stop before becoming data.
With strict options, ambiguous documents stop before becoming data.

Rejecting duplicate properties

A JSON document with the same property repeated twice is ambiguous: which value wins? Some attacks exploit exactly the difference in interpretation between systems. You can now ask the serializer to reject such documents.

var options = new JsonSerializerOptions
{
    AllowDuplicateProperties = false
};

// throws JsonException: "amount" appears twice
var json = "{ \"amount\": 10, \"amount\": 1000 }";
var p = JsonSerializer.Deserialize<Payment>(json, options);

A ready-made strict profile

JsonSerializerOptions.Strict bundles the strictest settings: no unknown properties, no duplicates, respect for nullable types and required constructor parameters. It is a good starting point for public APIs.

var order = JsonSerializer.Deserialize<Order>(json, JsonSerializerOptions.Strict);

Reading directly from PipeReader

High-performance applications such as ASP.NET Core read incoming data through a PipeReader. In .NET 10 the serializer can deserialise directly from this source, avoiding intermediate copies in memory.

Tips

  • Use source generation (JsonSerializerContext) for better performance and Native AOT compatibility.
  • Define shared options once and reuse them: creating them each time is expensive.
  • Prefer strict settings for incoming data; you can be more lenient for outgoing data.
Comments (0)

No comments yet.

Leave a comment