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].
using System.Text.Json; string json = JsonSerializer.Serialize(new { Name = "Ada", Age = 36 }); // {"Name":"Ada","Age":36}
Try it
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.
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
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 astatic readonlyfield or use the built-inJsonSerializerOptions.Webpreset (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 unlessWriteIndentedis 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
requiredmembers orJsonRequiredto reject incomplete input. - Attributes.
[JsonPropertyName("id")]renames,[JsonIgnore]skips,[JsonConverter]plugs in a custom converter,[JsonPropertyOrder]sets order. JsonDocumentvsJsonNode.JsonDocumentis read-only, uses pooled memory and must be disposed; do not keep aJsonElementafter disposal.JsonNodeis mutable and allocates more, so use it when you need to edit.- Streams for large data.
DeserializeAsyncandSerializeAsyncwork on streams without building a huge string.DeserializeAsyncEnumerablereads a JSON array element by element. - Source generation. For trimming, NativeAOT and fast startup, derive from
JsonSerializerContextand 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
dynamicsupport, no automatic parsing of numbers from strings (unless you opt in withNumberHandling), 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.
Related
Encoding, Records,StreamReader, JSON serialization- Lessons: JSON in C#, Records