Skip to content
Tutorials Center
My learning

Topics

Lesson 118 of 182 ยท Standard Library

JSON with System.Text.Json

Learn System.Text.Json in C# - serialize and deserialize objects and records, naming policies, attributes, JsonDocument, JsonNode, custom converters and polymorphism.

JSON is the language of web APIs, configuration files and many data stores. A JSON document is text made of objects ({ "name": "Ada" }), arrays ([1, 2, 3]), strings, numbers, booleans and null. Your C# program works with classes, records and collections instead, so you need a translator in both directions: serialization turns objects into JSON text and deserialization turns JSON text back into objects.

.NET ships a fast, built-in translator in the System.Text.Json namespace. It needs no NuGet package, it is what ASP.NET Core uses for every request and response, and it is available in our editor. In this lesson you will serialize and deserialize with the defaults, customize the output with options and attributes, handle bad input, read JSON without a matching class using JsonDocument and JsonNode, write custom converters, and see how polymorphism and source generation fit in.

Serializing an object

JsonSerializer.Serialize takes any object and returns a string. Public properties become JSON members:

C# Serialize an object

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.

By default the serializer:

  • includes public properties with getters (not fields, not private members),
  • keeps the C# property names (Title, not title),
  • writes null values,
  • escapes quotes (a " inside a string is written as the six characters backslash, u, 0, 0, 2, 2) and non-ASCII characters as \uXXXX and also <, >, & and ' for safety in HTML,
  • writes compact output without spaces.

All of this is configurable through JsonSerializerOptions.

Options: formatting, naming and nulls

C# JsonSerializerOptions

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.

Notice what changed: indented layout, orderId instead of OrderId, the enum written as the text "Shipped" instead of the number 1, and the null note missing entirely. Other naming policies: SnakeCaseLower (order_id), KebabCaseLower, SnakeCaseUpper, KebabCaseUpper (since .NET 8).

Create one JsonSerializerOptions instance and reuse it (put it in a static readonly field). The serializer caches reflection metadata per options instance; building new options for every call is slow and wastes memory.

ASP.NET Core uses web defaults: camelCase names and case-insensitive reading. You can get the same with new JsonSerializerOptions(JsonSerializerDefaults.Web).

Deserializing

JsonSerializer.Deserialize<T> builds an object from text. By default property-name matching is case-sensitive, so "title" does not fill a property called Title unless you turn on PropertyNameCaseInsensitive or use the web defaults:

C# Deserialize into classes and records

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.

Records with positional parameters work out of the box: the serializer calls the constructor and matches JSON members to parameter names. Unknown members are ignored. Missing members leave properties at their default values, which for reference types means null even if the type says non-nullable. That surprise is covered next.

Bad input and missing data

C# JsonException and missing members

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.

Step 1 fails because a trailing comma is not legal JSON unless you set AllowTrailingCommas = true. Step 2 reports the path of the member with the wrong type. Two defences worth knowing: the C# required modifier (also [JsonRequired]) turns a missing member into a JsonException, and TryDeserialize helpers do not exist, so wrap calls in try/catch (JsonException) whenever the text comes from outside your program.

Attributes

Attributes tune individual members without options:

C# JSON attributes

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 key ones: [JsonPropertyName] renames, [JsonIgnore] hides secrets, [JsonInclude] includes a property whose getter or setter is not public, [JsonPropertyOrder] controls ordering, [JsonRequired] demands presence, [JsonConstructor] picks the constructor, [JsonExtensionData] collects unknown members in a dictionary, and [JsonConverter] plugs in a custom converter.

Look at the result: Created comes first because of its negative order, PasswordHash and the null Nickname are missing, and Note (private setter) appears only because of [JsonInclude]. On the way back in, the lowercase "id" did not match the property Id, so it stayed 0, and PasswordHash was ignored even though the JSON contained it.

Dates, numbers and other types

DateTime, DateTimeOffset, Guid, TimeSpan, Uri, decimal, DateOnly and TimeOnly all have built-in support. Dates are written in ISO 8601 form; Guid as a string; TimeSpan as "01:30:00":

C# Built-in type formats

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.

JSON has one number type, and JavaScript reads it as a 64-bit float. Integers above 2^53 (such as long.MaxValue) lose precision in a browser. APIs that return big ids often send them as strings; JsonNumberHandling.WriteAsString does that for you.

Reading JSON without a class: JsonDocument

If the shape is unknown, or you want just one value out of a huge document, parse it into a read-only DOM with JsonDocument. It is very efficient because it keeps the raw bytes and hands out lightweight views:

C# JsonDocument

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.

Dispose the JsonDocument (it rents pooled memory). A JsonElement is only valid while its document is alive, so copy values out (GetString(), Clone()) before disposing. GetProperty throws KeyNotFoundException when the name is missing; TryGetProperty does not.

Editing JSON: JsonNode

JsonDocument is read-only. When you need to build or modify JSON, use the mutable DOM in System.Text.Json.Nodes: JsonObject, JsonArray, JsonValue:

C# JsonNode, JsonObject and JsonArray

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.

Indexing a missing key returns null (not an exception), so use ?. or the null-forgiving operator carefully. Prefer typed classes whenever the shape is known: they are faster and the compiler checks them. Use JsonNode for patching documents and for glue code.

Custom converters

When a type needs a special JSON shape, write a JsonConverter<T>. Here a Money struct is written as a short string like "12.50 EUR":

C# A custom JsonConverter

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 [JsonConverter] attribute on the type applies it everywhere. Alternatively add the converter to options.Converters to apply it for one options instance only. Utf8JsonReader and Utf8JsonWriter are the low-level forward-only reader and writer that everything else is built on; they are the fastest way to process JSON but need more code.

Polymorphism

By default the serializer writes the declared type's properties only. If Animal is the declared type but the object is a Dog, the dog-specific properties are lost on write, and reading cannot know which subclass to create. Since .NET 7 you can declare the allowed subtypes and a discriminator:

C# Polymorphic serialization

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 discriminator ("kind") must be the first property in the JSON object when reading, unless you set AllowOutOfOrderMetadataProperties. Only types you list are accepted: this closed list is also what makes polymorphic deserialization safe, because attackers cannot make the server instantiate arbitrary types.

Streams, files and async

Real programs seldom pass whole strings around. The serializer can read and write directly to a Stream, and also stream a large array element by element:

C# Serialize to a stream and stream an array

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.

DeserializeAsyncEnumerable yields each array element as soon as it has been read, so memory stays flat for a 2 GB JSON array. With HttpClient you will use the helpers GetFromJsonAsync<T> and PostAsJsonAsync that build on this (HttpClient).

Source generation

Reflection is flexible but slow at startup, and it does not work with trimming and Native AOT. A source generator produces the serialization code at compile time instead. You declare a partial context class and list your types:

C#
// Read-only: the editor compiles one file and does not run source generators for this pattern reliably.
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = true)]
[JsonSerializable(typeof(Order))]
[JsonSerializable(typeof(List<Order>))]
internal partial class AppJsonContext : JsonSerializerContext
{
}

// Usage: pass the generated metadata instead of options
string json = JsonSerializer.Serialize(order, AppJsonContext.Default.Order);
Order? back = JsonSerializer.Deserialize(json, AppJsonContext.Default.Order);

Benefits: faster first call, lower memory, trimming and AOT safety. Cost: a little ceremony, and every type you serialize must be listed. ASP.NET Core minimal APIs can use the same context via ConfigureHttpJsonOptions. Reach for it in libraries, high-traffic services and AOT apps; for a small tool, plain reflection is fine.

Common pitfalls

  • Forgetting that names are case-sensitive on read (use JsonSerializerDefaults.Web).
  • Creating new JsonSerializerOptions per call.
  • Expecting fields to be serialized (set IncludeFields = true or use properties).
  • Expecting the declared type's properties of a subclass; use [JsonDerivedType].
  • Trusting JSON from outside: validate after deserializing, and never deserialize into types whose constructors do dangerous work.
  • Using Newtonsoft.Json habits: JObject maps to JsonNode, JsonProperty to JsonPropertyName.
  • Cyclic object graphs throw; set ReferenceHandler = ReferenceHandler.Preserve or break the cycle.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. By default, which members does JsonSerializer.Serialize include?

    The default is public properties with getters. Fields need IncludeFields = true and private members need [JsonInclude] on a public member.
  2. 2. JSON has "title" but your class has Title. Deserializing with default options gives what?

    Matching is case-sensitive by default. Use PropertyNameCaseInsensitive = true or JsonSerializerDefaults.Web.
  3. 3. When is JsonDocument the right choice?

    JsonDocument is a read-only, low-allocation view. Use JsonNode when you need to modify.
  4. 4. What is the recommended way to share serializer settings?

    Options hold cached metadata; creating them repeatedly is slow.
  5. 5. Which attribute pair makes Shape deserialize into Circle or Rectangle?

    Declare the allowed subtypes with [JsonDerivedType] and (optionally) configure the discriminator with [JsonPolymorphic].

Summary

  • JsonSerializer.Serialize and Deserialize<T> convert objects to and from JSON; public properties are used by default.
  • Configure with a reusable JsonSerializerOptions (indentation, naming policy, ignore nulls, enum strings, web defaults) and tune members with attributes.
  • Malformed or mistyped JSON throws JsonException; use required to reject missing members.
  • JsonDocument reads without classes; JsonNode reads and edits.
  • JsonConverter<T> customizes the shape of a type; [JsonDerivedType] enables safe polymorphism.
  • Stream large data with SerializeAsync and DeserializeAsyncEnumerable.
  • Source generation removes reflection for speed and AOT.

Next: XML, CSV and Other Formats