How to Implement Custom JSON Converters in ASP.NET Core 10 Using System.Text.Json

A System.Text.Json converter defines how a .NET type maps to JSON. Use one when an external contract requires a wire format the built-in serializer cannot express. In this lab, a partner sends dates as eight-digit strings such as “20261205”. The converter parses that format explicitly and emits the same format on the response.

Read JSON string. Parse exact yyyyMMdd. Bind a DateOnly value. Write the agreed format. Malformed values produce a binding error
Convert a legacy date.

Keep the contract narrow

Use JsonConverter for a specific closed type. JsonConverterFactory is for a family of related types, such as a generic wrapper. Prefer the built-in enum converter if its documented behavior meets your contract. For polymorphic types, configure known discriminators and derived types explicitly. Never resolve an arbitrary CLR type from input.

A DateOnly converter registered globally changes every DateOnly using those options. For a single property or a single integration, scope the converter using a property attribute, a dedicated transport type, or options used only by that integration. The lab registers it for both controller and minimal API JSON options to demonstrate the two pipelines.

Create an empty ASP.NET Core Web project targeting .NET 10, replace Program.cs, then run the app on loopback. Use these commands from the parent directory.

dotnet new web -n Lab -f net10.0
cd Lab
dotnet run --no-launch-profile --urls http://localhost:5080

Program.cs

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

var builder = WebApplication.CreateBuilder(args);
builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.Converters.Add(new LegacyDateConverter()));
builder.Services.AddControllers().AddJsonOptions(o => o.JsonSerializerOptions.Converters.Add(new LegacyDateConverter()));
var app = builder.Build();
app.MapPost("/minimal", (Shipment shipment) => shipment);
app.MapControllers();
app.Run();

public record Shipment(DateOnly Date);
public sealed class LegacyDateConverter : JsonConverter<DateOnly>
{
    private const string Format = "yyyyMMdd";

    public override DateOnly Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.String &&
            DateOnly.TryParseExact(reader.GetString(), Format, CultureInfo.InvariantCulture,
                DateTimeStyles.None, out var value))
            return value;
        throw new JsonException("Expected a calendar date in yyyyMMdd format.");
    }

    public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
        => writer.WriteStringValue(value.ToString(Format, CultureInfo.InvariantCulture));
}

[Microsoft.AspNetCore.Mvc.ApiController]
[Microsoft.AspNetCore.Mvc.Route("controller")]
public sealed class ShipmentsController : Microsoft.AspNetCore.Mvc.ControllerBase
{
    [Microsoft.AspNetCore.Mvc.HttpPost]
    public Shipment Post(Shipment shipment) => shipment;
}

Check accepted and rejected requests

Post {“date”:“20260228”} to /minimal and /controller. Each returns the same string. Post {“date”:“20260230”}, {“date”:“2026-02-28”}, and {“date”:20260228}. Expect a binding error because the string must match an actual date in the chosen format. A missing property is a separate contract concern. Mark required fields explicitly when omission must fail. For nullable properties, decide whether explicit null is valid. System.Text.Json commonly handles null without invoking a custom converter for nullable and reference values unless the converter opts in.

Avoid common implementation failures

Throw JsonException for malformed JSON values so the serializer can supply path context. The converter must consume exactly one value. A scalar converter can read the current token directly. For object and array converters, test nesting and reader advancement. Calling JsonSerializer.Deserialize with the same target type and the same registered converter can recurse. Delegate only to a different type or an options instance with a clear converter setup.

Reuse serializer options and keep converter instances stateless. Test representative payloads before optimizing. Source generation can help serializer setup and metadata costs, while your converter’s parsing and allocations remain your responsibility.

When should I avoid a converter? If an internal API can use the default ISO date representation, keep the standard contract. A converter is most useful when an external producer or consumer requires a different format.

Comments