Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Files and I/O

JSON serialization with System.Text.Json

Reference for JsonSerializer in C#: Serialize and Deserialize, JsonSerializerOptions, naming policies, attributes, enums, records and JsonException.

System.Text.Json.JsonSerializer converts .NET objects to JSON text and back. JsonSerializer.Serialize(value) produces a string, and JsonSerializer.Deserialize<T>(json) parses a string into an object of type T. The serializer reads public properties (and public fields if you ask) by reflection, supports records, collections, dictionaries, nullable types, enums and nested objects, and is built into the shared framework, so no NuGet package is needed.

Behavior is controlled by JsonSerializerOptions and by attributes such as [JsonPropertyName] and [JsonIgnore]. Create one options object and reuse it: the serializer caches metadata per options instance, so building a new one for each call is slow.

C#
var json = JsonSerializer.Serialize(new { Name = "Ada", Age = 36 });
// {"Name":"Ada","Age":36}
var person = JsonSerializer.Deserialize<Person>(json);

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# Attributes, errors and flexible 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.

Syntax

C#
public static string Serialize<TValue>(TValue value, JsonSerializerOptions? options = null);
public static string Serialize(object? value, Type inputType, 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 static byte[] SerializeToUtf8Bytes<TValue>(TValue value, JsonSerializerOptions? options = null);
Name Description
value The object to write. null becomes the JSON literal null.
json / utf8Json The JSON text, or a stream of UTF-8 JSON.
options Optional JsonSerializerOptions. Key settings: WriteIndented, PropertyNamingPolicy, PropertyNameCaseInsensitive, DefaultIgnoreCondition, NumberHandling, IncludeFields, AllowTrailingCommas, ReadCommentHandling, Converters, MaxDepth.
Attributes [JsonPropertyName], [JsonIgnore], [JsonInclude], [JsonConstructor], [JsonConverter], [JsonRequired], [JsonDerivedType].

Returns: a JSON string or byte array, or the deserialized object (which is null when the JSON is the literal null).

Errors: JsonException for invalid JSON, type mismatches and missing [JsonRequired] members (its Path, LineNumber and BytePositionInLine say where); ArgumentNullException for a null string; NotSupportedException for types without a usable converter.

Usage notes

  • Reuse the options. Store JsonSerializerOptions in a static readonly field. Once the options have been used for serialization they become read-only; changing them later throws InvalidOperationException.
  • Defaults are strict and fast. Names are matched case-sensitively, trailing commas and comments are rejected, numbers must be numbers, and the output is compact and not indented. JsonSerializerDefaults.Web switches to the conventions used by web APIs.
  • Properties, not fields. Only public properties with a getter (and setter, or a matching constructor parameter) take part. Set IncludeFields = true or use [JsonInclude] for public fields and non-public setters.
  • Records work. Positional records are deserialized through their primary constructor; parameter names are matched to JSON names case-insensitively.
  • Enums are numbers by default. Add JsonStringEnumConverter (or [JsonConverter(typeof(JsonStringEnumConverter))] on the enum) to write names.
  • DateTime, Guid and decimal are supported. DateTime uses ISO 8601. long values above 2^53 lose precision in JavaScript clients; send them as strings with NumberHandling or a converter.
  • Polymorphism. The serializer writes the static type's properties only. Declare the base type with [JsonDerivedType] to write a type discriminator, or serialize with object as the type.
  • Untrusted input. Limit the request size and keep MaxDepth at its default (64) to avoid abuse; System.Text.Json does not instantiate arbitrary types from the input like some older libraries.
  • Source generation. JsonSerializerContext removes reflection and helps trimming and native AOT, but it needs a source generator that this site's runner does not have, so those examples cannot run here.
  • Dynamic structure. When the shape is unknown, use JsonDocument (read-only, pooled) or JsonNode (editable) instead of Deserialize.
  • Differences from Newtonsoft.Json. System.Text.Json is stricter by default, and has no built-in support for some things such as ExpandoObject and JObject-style paths.