Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Strings and Text

System.Text.Json

Reference for System.Text.Json in C#: JsonSerializer, JsonSerializerOptions, JsonDocument, JsonNode, attributes, and common serialization mistakes.

System.Text.Json is the JSON library built into .NET. It converts objects to JSON text (JsonSerializer.Serialize), JSON text back to objects (Deserialize<T>), and lets you inspect JSON without a matching class through JsonDocument (read-only, pooled) or JsonNode (a mutable tree). It works on UTF-8 internally, which makes it fast and light on allocations.

Its defaults are strict and predictable: property names are written as they appear in your classes, matching is case-sensitive when reading, comments and trailing commas are errors, and fields are ignored. You change this with JsonSerializerOptions or with attributes such as [JsonPropertyName] and [JsonIgnore].

C#
using System.Text.Json;

string json = JsonSerializer.Serialize(new { Name = "Ada", Age = 36 });
// {"Name":"Ada","Age":36}

Try it

C# Serialize and deserialize

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.

C# Reading JSON without a class

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.

Syntax

C#
public static class JsonSerializer
{
    public static string Serialize<TValue>(TValue value, JsonSerializerOptions? options = null);
    public static TValue? Deserialize<TValue>(string json, JsonSerializerOptions? options = null);
    public static ValueTask<TValue?> DeserializeAsync<TValue>(Stream utf8Json, JsonSerializerOptions? options = null,
                                                              CancellationToken cancellationToken = default);
    public static Task SerializeAsync<TValue>(Stream utf8Json, TValue value, JsonSerializerOptions? options = null,
                                              CancellationToken cancellationToken = default);
}

public sealed class JsonDocument : IDisposable
{
    public static JsonDocument Parse(string json, JsonDocumentOptions options = default);
    public JsonElement RootElement { get; }
}
Name Description
value The object to write. Public properties are included by default; public fields only with IncludeFields = true.
json / utf8Json The JSON text or a stream of UTF-8 bytes.
options A JsonSerializerOptions: naming policy, indentation, case sensitivity, comments, trailing commas, number handling, converters. Create one instance and reuse it.
JsonDocumentOptions Controls comments, trailing commas and maximum depth when parsing.

Returns: Serialize returns a string. Deserialize returns the object, or null when the JSON is the literal null.

Errors / undefined behavior: malformed JSON or a value that does not fit the target type throws JsonException. A null argument throws ArgumentNullException. Reading a property from a JsonElement with the wrong getter (for example GetInt32 on a string) throws InvalidOperationException, and GetProperty for a missing name throws KeyNotFoundException.

Usage notes

  • Reuse JsonSerializerOptions. The options object caches type metadata. Creating a new one per call is slow and allocates a lot; make it a static readonly field or use the built-in JsonSerializerOptions.Web preset (camelCase, case-insensitive, string numbers allowed).
  • Defaults to remember. Names are not changed unless you set a naming policy. Reading is case-sensitive. Enums are numbers unless you add JsonStringEnumConverter. Comments and trailing commas throw. Output is compact unless WriteIndented is true.
  • Records and constructors work. A positional record is deserialized through its primary constructor, as the first example shows. Missing members get their default values; use required members or JsonRequired to reject incomplete input.
  • Attributes. [JsonPropertyName("id")] renames, [JsonIgnore] skips, [JsonConverter] plugs in a custom converter, [JsonPropertyOrder] sets order.
  • JsonDocument vs JsonNode. JsonDocument is read-only, uses pooled memory and must be disposed; do not keep a JsonElement after disposal. JsonNode is mutable and allocates more, so use it when you need to edit.
  • Streams for large data. DeserializeAsync and SerializeAsync work on streams without building a huge string. DeserializeAsyncEnumerable reads a JSON array element by element.
  • Source generation. For trimming, NativeAOT and fast startup, derive from JsonSerializerContext and mark it with [JsonSerializable(typeof(T))]. The generator needs the Roslyn source-generator pipeline, which this site's runner does not offer, so such code is read-only here.
  • Differences from Newtonsoft.Json. System.Text.Json is stricter and has no dynamic support, no automatic parsing of numbers from strings (unless you opt in with NumberHandling), and ignores fields by default.
  • Security. Untrusted JSON can be deeply nested. The default maximum depth is 64, which protects the parser; keep it unless you must raise it.