Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 52 ยท Models, Validation and Serialization

JSON Serialization in APIs

Control JSON in ASP.NET Core APIs: web defaults, naming policies, enums, custom converters, polymorphism and the shared JsonSerializerOptions.

Almost every API you write speaks JSON. When a minimal API endpoint returns a record, something turns it into text; when a client posts a body, something turns text back into a C# object. In ASP.NET Core that something is System.Text.Json, the serializer built into .NET. It is fast and strict by default, and a handful of options change its behavior.

In this lesson you will see what the web defaults do, how to change naming and enum formats for the whole app, how to shape individual types with attributes and converters, and how to describe inheritance with polymorphic JSON. The C# track has a general introduction to the library in JSON in C#; this lesson is about how it plugs into the request pipeline.

The web defaults

JsonSerializer on its own uses conservative defaults (PascalCase names, exact-case matching). ASP.NET Core applies the JsonSerializerDefaults.Web preset instead, which means:

  • property names are written in camelCase (UnitPrice becomes unitPrice);
  • reading is case-insensitive ("ID", "Id" and "id" all bind to Id);
  • numbers inside quotes are accepted for numeric properties on read.

Everything else stays at the library defaults: null values are written, enums are written as numbers, and unknown properties in a request body are silently ignored.

flowchart LR
    A["Request body<br/>JSON text"] --> B["JsonSerializerOptions<br/>(web defaults + your changes)"]
    B --> C["C# object<br/>endpoint parameter"]
    C --> D["Endpoint code"]
    D --> E["Return value"]
    E --> B
    B --> F["Response body<br/>JSON text"]

One set of options is used in both directions: reading the request and writing the response.

C# What the web defaults do

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The output shows camelCase names, status as the number 1, and note written as null. The POST succeeds even though the body used ID and NAME and a price in quotes. The two bad requests never reach your lambda: binding fails and the framework answers 400 Bad Request (the lesson on parameter binding shows how to take control of that).

Changing the options for the whole app

Minimal APIs read their options from Microsoft.AspNetCore.Http.Json.JsonOptions, which you configure with ConfigureHttpJsonOptions. Settings made here affect every endpoint that returns or accepts JSON.

The options you will reach for most:

Option Effect
PropertyNamingPolicy How C# names become JSON names (CamelCase by default; SnakeCaseLower, KebabCaseLower also built in)
DefaultIgnoreCondition WhenWritingNull omits null properties from responses
Converters.Add(new JsonStringEnumConverter()) Writes and reads enums as names instead of numbers
UnmappedMemberHandling Disallow rejects request bodies with properties your type does not have
WriteIndented Pretty-printed output (use only for debugging: it is larger)

Attributes give per-type and per-property control: [JsonPropertyName("total_cents")] renames one property (and wins over the naming policy), [JsonIgnore] hides a property in both directions, and [JsonConverter(...)] picks a converter for a type.

C# App-wide options, attributes and strict input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Study the first line: names are snake_case, the enum is paymentPending, Coupon is omitted because it is null, InternalNote never leaves the server, and the explicit [JsonPropertyName("totalCents")] beat the naming policy. On the way in, UnmappedMemberHandling.Disallow turned an unexpected is_admin property into a 400. That is a cheap defense against clients (or attackers) sending fields they should not control; the lesson on DTOs explains the deeper fix, which is to bind to a small request type.

MVC controllers have their own JSON options, configured with AddControllers().AddJsonOptions(...). Changing ConfigureHttpJsonOptions does not change controllers, and the reverse is also true. If an app mixes both styles, configure both. See Controllers and Actions.

Custom converters

Sometimes a type should look different on the wire than it does in memory. A converter is a class that reads and writes one type. Here a Money value is exchanged as a single string such as "12.50 USD" instead of an object with two members.

You derive from JsonConverter<T>, implement Read and Write, and attach the converter with an attribute on the type (or add it to Converters for the whole app).

Polymorphism

Serializing a base type normally writes only the base type's properties, and reading cannot know which derived type to create. .NET 7 and later solve this with attributes. [JsonPolymorphic] on the base type turns on a type discriminator (an extra property such as "kind"), and each [JsonDerivedType] maps a derived class to a discriminator value.

C# A custom converter and a polymorphic hierarchy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two details deserve attention. The converter turns Money into "12.50 USD" in both directions, so clients never see the two-field object. And polymorphism relies on the declared type: the endpoint returns Shape[], so the serializer knows to add "kind". If you returned new Circle(1) typed as Circle, the discriminator would be missing, and a body with an unknown "kind" such as triangle is rejected with a 400.

Polymorphic deserialization decides which types a client may make you create. Only list types in [JsonDerivedType] that you are happy to receive, and never enable arbitrary type names from the payload. System.Text.Json has no such feature, and that is on purpose.

Practical advice

  • Pick one naming convention and apply it app-wide. camelCase is the default and what most JavaScript clients expect; do not mix styles per endpoint.
  • Prefer string enums in public APIs. Numbers break the moment you insert a value in the middle of an enum, and names read better in logs and OpenAPI documents.
  • Hide internal fields with DTOs, not just [JsonIgnore]. [JsonIgnore] on an entity is easy to forget when you add a property. A separate response type is explicit.
  • Prefer DateTimeOffset over DateTime for instants so the offset travels with the value, and use ISO 8601 (the default).
  • Return Results.Json(value, options) only for exceptions. One shared options object is easier to reason about than per-call options. The lesson on responses and results covers when to use Results.Json.
  • Expect big numbers to need care. JavaScript clients lose precision above 2^53, so send very large identifiers as strings.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which behavior belongs to the ASP.NET Core web defaults for JSON?

    The web preset uses camelCase names and case-insensitive reading. Enums as numbers and writing nulls remain the library defaults until you change them.
  2. 2. Where do you configure the JSON options that minimal API endpoints use?

    ConfigureHttpJsonOptions sets the options for minimal APIs. Controllers use their own options, set with AddJsonOptions.
  3. 3. What does JsonUnmappedMemberHandling.Disallow do when reading a request body?

    With Disallow, extra properties cause a JsonException and the framework answers 400, which helps stop clients from sending fields they should not control.
  4. 4. An endpoint returns new Circle(1) typed as Circle, and Shape has [JsonPolymorphic]. What is the likely result?

    Polymorphic metadata is applied when the declared type is the base type. Serialized as Circle, no discriminator is written.
  5. 5. Why is [JsonPropertyName("totalCents")] helpful even when a naming policy is configured?

    An explicit name from the attribute wins over the naming policy, in both reading and writing.

Summary

  • ASP.NET Core serializes with System.Text.Json using web defaults: camelCase names, case-insensitive reading, enums as numbers, nulls written.
  • ConfigureHttpJsonOptions changes naming, null handling, enum format and strictness for every minimal API endpoint; controllers have separate options.
  • Attributes ([JsonPropertyName], [JsonIgnore], [JsonConverter]) shape single types; custom converters control the wire format of a type.
  • [JsonPolymorphic] plus [JsonDerivedType] describes inheritance with a discriminator and relies on the declared type when writing.
  • UnmappedMemberHandling.Disallow rejects unexpected input; string enums and DTOs make public contracts safer.

Next: Model Validation