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.
var json = JsonSerializer.Serialize(new { Name = "Ada", Age = 36 }); // {"Name":"Ada","Age":36} var person = JsonSerializer.Deserialize<Person>(json);
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 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
JsonSerializerOptionsin astatic readonlyfield. Once the options have been used for serialization they become read-only; changing them later throwsInvalidOperationException. - 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.Webswitches 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 = trueor 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,Guidanddecimalare supported.DateTimeuses ISO 8601.longvalues above 2^53 lose precision in JavaScript clients; send them as strings withNumberHandlingor 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 withobjectas the type. - Untrusted input. Limit the request size and keep
MaxDepthat its default (64) to avoid abuse;System.Text.Jsondoes not instantiate arbitrary types from the input like some older libraries. - Source generation.
JsonSerializerContextremoves 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) orJsonNode(editable) instead ofDeserialize. - Differences from Newtonsoft.Json.
System.Text.Jsonis stricter by default, and has no built-in support for some things such asExpandoObjectandJObject-style paths.
Related
XmlSerializer,XDocument,HttpClient, Records- Lessons: JSON, Records