skip to content

JSON Options & Formatters

System.Text.Json with web defaults handles bodies, tuned via AddJsonOptions or ConfigureHttpJsonOptions; formatters and [Produces] drive content negotiation. Interviewers probe casing and 406s.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

6

In ASP.NET Core 10, why does a C# property named TrackingNumber come out of an API as trackingNumber, and which other JSON defaults apply?

level: juniorimportance: must knowfreq 62%

answer

  1. one preset for web JSON
  2. JsonSerializerDefaults.Web
  3. JsonNamingPolicy.CamelCase on write
  4. PropertyNameCaseInsensitive on read
  5. AllowReadingFromString for numbers

basics

~10 s

ASP.NET Core builds its System.Text.Json options from JsonSerializerDefaults.Web: property names are written in camelCase, read case-insensitively, and numbers may arrive as JSON strings. Setting PropertyNamingPolicy to null keeps the C# names.

solid answer

~30 s

Both MVC controllers and Minimal APIs create their `JsonSerializerOptions` from `JsonSerializerDefaults.Web`. That preset sets `PropertyNamingPolicy = JsonNamingPolicy.CamelCase`, so `TrackingNumber` is written as `trackingNumber`; it sets `PropertyNameCaseInsensitive = true`, so a client posting `TRACKINGNUMBER` or `trackingnumber` still binds; and it sets `NumberHandling = JsonNumberHandling.AllowReadingFromString`, so `"1200"` binds to an `int`. What it does not change: enums are still written as numbers, and null properties are still written. To keep PascalCase, set `PropertyNamingPolicy = null` in the options; to rename one property, put `[JsonPropertyName("tracking_no")]` on it. `ProblemDetails` keeps lowercase names either way, because its properties carry their own `[JsonPropertyName]` attributes.

code

csharp · 18 lines
csharp
using System.Text.Json;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers()
    .AddJsonOptions(o =>
    {
        // keep C# names: TrackingNumber stays TrackingNumber
        o.JsonSerializerOptions.PropertyNamingPolicy = null;
        // stop writing "reference": null
        o.JsonSerializerOptions.DefaultIgnoreCondition =
            JsonIgnoreCondition.WhenWritingNull;
    });

var app = builder.Build();
app.MapControllers();
app.Run();

go deeper

for a junior

Recall that responses are camelCase by default, that input names match case-insensitively, and that PropertyNamingPolicy = null or [JsonPropertyName] changes it.

for a middle

Name JsonSerializerDefaults.Web and the three settings it changes, and explain why enums stay numeric and nulls are still written.

for a senior

Decide deliberately whether to keep lenient defaults such as quoted numbers, and know which scope (app, property, endpoint) a casing change belongs at.

for a principal

Treat JSON casing and leniency as part of the public contract: standardise one policy across services so clients never see mixed casing.

## Where the casing comes from ASP.NET Core serializes request and response bodies with **System.Text.Json**. It does not use that library's bare defaults; it starts from the **web preset**, `JsonSerializerDefaults.Web`. In ASP.NET Core 10 both option types do this: - MVC's `Microsoft.AspNetCore.Mvc.JsonOptions` creates `JsonSerializerOptions` with `new JsonSerializerOptions(JsonSerializerDefaults.Web)` and also sets `MaxDepth` to 32. - Minimal APIs' `Microsoft.AspNetCore.Http.Json.JsonOptions` copies a default instance that is built from the same preset. So in a shipping-label API, this C# type: ```csharp public class ShippingLabel { public string TrackingNumber { get; set; } = ""; public int WeightGrams { get; set; } public LabelFormat Format { get; set; } public string? Reference { get; set; } } ``` is written as `{"trackingNumber":"1Z999","weightGrams":1200,"format":1,"reference":null}`. ## What the web preset switches on | Setting | Web preset value | Effect on a request or response | |---|---|---| | `PropertyNamingPolicy` | `JsonNamingPolicy.CamelCase` | Output names are camelCase | | `PropertyNameCaseInsensitive` | `true` | `TrackingNumber`, `trackingNumber` and `TRACKINGNUMBER` all bind on input | | `NumberHandling` | `JsonNumberHandling.AllowReadingFromString` | `"weightGrams": "1200"` binds to an `int` | The last row surprises people: since .NET 5, an ASP.NET Core app accepts quoted numbers by default, while a plain `JsonSerializer.Deserialize` call with default options rejects them. ## What the preset leaves alone - **Enums** are still written as their numeric value (`"format": 1`). Names need a `JsonStringEnumConverter`. - **Nulls** are still written. Leaving them out takes `DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull`. - **Fields** are not serialized; only public properties are. - **Unknown JSON properties** in a request are ignored rather than rejected. ## Changing the casing There are three levels, from broad to narrow: 1. **App-wide:** set `PropertyNamingPolicy` in the options. `null` keeps C# names exactly; `JsonNamingPolicy.SnakeCaseLower` gives `tracking_number`. 2. **Per property:** `[JsonPropertyName("tracking_no")]` overrides the policy for one member, in both directions. 3. **Per response:** pass your own `JsonSerializerOptions` to a JSON result (for example `new JsonResult(label, options)` in a controller) when a single endpoint must differ. ```csharp builder.Services.AddControllers() .AddJsonOptions(o => o.JsonSerializerOptions.PropertyNamingPolicy = null); ``` That line only affects controllers; Minimal API endpoints read a different option type, which is a separate question. ## ProblemDetails is the exception Error bodies keep lowercase member names (`type`, `title`, `status`, `detail`, `instance`) even after you switch the app to PascalCase. The `ProblemDetails` class puts `[JsonPropertyName]` on each of its properties, and an attribute beats the naming policy. Clients therefore see consistent error shapes whatever casing the rest of the API uses. ## Minimal APIs and controllers agree Because both option types start from the same preset, a Minimal API endpoint and a controller action return the same casing out of the box. They only diverge once someone changes one option type and not the other; every override shown above has to be applied to each stack you use. A quick way to see the effective output is to call the endpoint with `curl` or an `.http` file and read the raw body, rather than trusting a client library that may re-map names on its side. ## Symptoms and their causes | Symptom | Cause | |---|---| | A JavaScript client reads `label.TrackingNumber` and gets `undefined` | the API writes `trackingNumber`; the client used the C# name | | A partner's PascalCase request binds although the docs show camelCase | case-insensitive reading is part of the web preset | | A strict client fails on `"reference": null` | nulls are written unless `DefaultIgnoreCondition` says otherwise | | A shared library serializes the same type with different names | it calls `JsonSerializer` with default options, not the web preset; `JsonSerializerOptions.Web` gives the same preset there | ## Why this matters in an interview - A front-end developer reports that `TrackingNumber` is "missing" from the response: it is there, as `trackingNumber`. - A client sends PascalCase and it works anyway: that is case-insensitive reading, not a bug. - A partner sends `"weightGrams": "1200"` and it binds: that is `AllowReadingFromString`, and some teams switch it off to keep the contract strict. The interviewer wants to hear the name of the preset, the three settings it changes, and how to override them at the right scope.

  • A client posts {"weightGrams": "1200"} and it binds to an int. Is that a bug, and how would you make the contract strict?
    It is the web preset: `NumberHandling` is `JsonNumberHandling.AllowReadingFromString`, so quoted numbers are accepted. To reject them, set `NumberHandling = JsonNumberHandling.Strict` in the app's JSON options; the formatter then fails the read and `ModelState` records a binding error, which an `[ApiController]` turns into a 400.
  • After switching the app to PascalCase, why does a validation error body still use lowercase title and status?
    `ProblemDetails` and `ValidationProblemDetails` declare `[JsonPropertyName]` on their standard members (`type`, `title`, `status`, `detail`, `instance`), and an explicit attribute overrides the naming policy. Error bodies therefore keep the RFC's lowercase names regardless of the app-wide policy.

  • ASP.NET Core uses System.Text.Json's bare defaults, so output keeps PascalCase names.
  • Property name matching on input is case-sensitive, so PascalCase requests fail to bind.
  • The web defaults also write enums as their member names.
  • Quoted numbers like "1200" are always rejected when binding an int property.
  • Newtonsoft.Json is still the default serializer in ASP.NET Core 10.
open as a page

In ASP.NET Core 10, why does ConfigureHttpJsonOptions leave controller responses unchanged, and how do you configure JSON for both controllers and Minimal APIs?

level: middleimportance: must knowfreq 48%

basics

~10 s

Controllers and Minimal APIs read two different option types that are both named JsonOptions. AddJsonOptions configures MVC's formatters; ConfigureHttpJsonOptions configures Minimal APIs and the request/response JSON helpers. An app with both needs both calls.

open as a page

In an ASP.NET Core 10 API, how do you send and accept enum values as names such as "Zpl" instead of numbers?

level: middleimportance: should knowfreq 52%

basics

~10 s

Enums serialize as numbers by default. Add JsonStringEnumConverter to the JSON options of each stack, or put [JsonConverter(typeof(JsonStringEnumConverter<LabelFormat>))] on the enum; pass a naming policy for camelCase names and allowIntegerValues: false to reject numbers.

open as a page

Why does returning an EF Core entity with back-references from an ASP.NET Core 10 controller throw a JsonException, and how do you fix it?

level: middleimportance: should knowfreq 45%

basics

~10 s

System.Text.Json follows navigation properties, so Shipment.Parcels[0].Shipment loops until the depth limit (32 in MVC) and throws a JsonException. Return a DTO without back-references, or set ReferenceHandler.IgnoreCycles or Preserve in the JSON options.

open as a page

In ASP.NET Core 10, how do you build a JSON Patch endpoint, and why is AddNewtonsoftJson no longer the default route to it?

level: seniorimportance: should knowfreq 32%

basics

~10 s

ASP.NET Core 10 adds Microsoft.AspNetCore.JsonPatch.SystemTextJson: bind a JsonPatchDocument<T> and call ApplyTo with an error callback. The older Microsoft.AspNetCore.JsonPatch is Newtonsoft-based and was usually wired with AddNewtonsoftJson, which replaces System.Text.Json formatters across the app.

open as a page

A legacy partner calls an ASP.NET Core 10 controller API with XML only; how do you support it, and when does the partner get 406 or 415?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Call AddXmlSerializerFormatters on AddControllers, then mark the partner's actions [Consumes("application/xml")] and [Produces("application/xml")]. A mismatched Content-Type gets 415; an unsatisfiable Accept gets 406 only when MvcOptions.ReturnHttpNotAcceptable is true, otherwise the response falls back to a default format.

open as a page