System.Text.Json
suggest changeSystem.Text.Json is the JSON library built into .NET (since .NET Core 3.0). It's fast, allocates little, works directly with UTF-8 bytes, and supports trimming and Native AOT through source generation. For new code it's the default choice. ASP.NET Core, HttpClient's GetFromJsonAsync/PostAsJsonAsync and the configuration system all use it.
The library has three layers:
JsonSerializerconverts between .NET objects and JSON.JsonNode(mutable) andJsonDocument(read-only) give DOM access when you don't have a matching type.Utf8JsonReaderandUtf8JsonWriterare low-level, forward-only APIs that the other two are built on.
The older Json.NET (Newtonsoft.Json) is still popular and has more features in some areas, but it's slower and doesn't support AOT. See Getting started with JSON in C# for Json.NET examples.
The examples are C# 14 / .NET 10 file-based apps: save the code as app.cs and run dotnet run app.cs. File-based apps default to Native AOT settings, which turn off reflection-based serialization, so most examples start with #:property PublishAot=false. A normal project doesn't need that line. The source generation section below shows the AOT-friendly way.
Serialize and deserialize
#:property PublishAot=false
using System.Text.Json;
var p = new Person("Alice", 30, ["C#", "Go"], new DateTime(2026, 10, 18, 9, 30, 0));
string json = JsonSerializer.Serialize(p);
Console.WriteLine(json);
var indented = new JsonSerializerOptions { WriteIndented = true };
Console.WriteLine(JsonSerializer.Serialize(p, indented));
Person? back = JsonSerializer.Deserialize<Person>(json);
Console.WriteLine(back);
Console.WriteLine(back!.Languages[1]);
// collections, dictionaries and anonymous types work too
var scores = new Dictionary<string, int> { ["alice"] = 10, ["bob"] = 7 };
Console.WriteLine(JsonSerializer.Serialize(scores));
Console.WriteLine(JsonSerializer.Serialize(new { Id = 1, Tags = new[] { "a", "b" }, Missing = (string?)null }));
int[] nums = JsonSerializer.Deserialize<int[]>("[1, 2, 3]")!;
Console.WriteLine(nums.Sum());
byte[] utf8 = JsonSerializer.SerializeToUtf8Bytes(p);
Console.WriteLine($"{utf8.Length} bytes");
record Person(string Name, int Age, List<string> Languages, DateTime Joined);
{"Name":"Alice","Age":30,"Languages":["C#","Go"],"Joined":"2026-10-18T09:30:00"}
{
"Name": "Alice",
"Age": 30,
"Languages": [
"C#",
"Go"
],
"Joined": "2026-10-18T09:30:00"
}
Person { Name = Alice, Age = 30, Languages = System.Collections.Generic.List`1[System.String], Joined = 10/18/2026 9:30:00 }
Go
{"alice":10,"bob":7}
{"Id":1,"Tags":["a","b"],"Missing":null}
6
80 bytes
The basics:
Serializewrites public properties (not fields) of the object, in declaration order.Deserialize<T>creates aTand fills it. It can call a constructor, so records and other immutable types work: constructor parameters are matched to JSON properties by name.- The default output is compact.
WriteIndented = truemakes it readable. Deserialize<T>returnsT?. JSONnullgives younull. Invalid JSON, or a value that doesn't fit the type (a string for anint), throwsJsonExceptionwith the path and position.DateTimeandDateTimeOffsetare written in ISO 8601 format.SerializeToUtf8Bytesskips the UTF-16 string. JSON on the wire and in files is UTF-8, so byte-based APIs are faster.
JsonSerializerOptions
JsonSerializerOptions controls naming, formatting, which values are written, and much more. Create an options instance once and reuse it (for example, in a static readonly field). The serializer caches metadata per options instance, so creating new options for every call is slow.
#:property PublishAot=false
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
var order = new Order(42, "Zoë <zoe@example.com>", OrderStatus.InTransit, 19.99m, null);
// JsonSerializerOptions.Web: camelCase names, case-insensitive reads, numbers may be quoted
Console.WriteLine(JsonSerializer.Serialize(order, JsonSerializerOptions.Web));
var snake = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower) },
};
Console.WriteLine(JsonSerializer.Serialize(order, snake));
var kebab = new JsonSerializerOptions(JsonSerializerOptions.Web)
{
PropertyNamingPolicy = JsonNamingPolicy.KebabCaseLower,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
WriteIndented = true,
IndentSize = 4,
};
Console.WriteLine(JsonSerializer.Serialize(order, kebab));
// reading: Web options match names case-insensitively and accept "19.99" as a number
string input = """{"ORDERID": 7, "customer": "Bob", "status": 1, "total": "5.50"}""";
Console.WriteLine(JsonSerializer.Deserialize<Order>(input, JsonSerializerOptions.Web));
// JsonSerializerOptions.Default is read-only
try { JsonSerializerOptions.Default.WriteIndented = true; }
catch (InvalidOperationException e) { Console.WriteLine(e.GetType().Name); }
enum OrderStatus { Pending, Shipped, InTransit }
record Order(int OrderId, string Customer, OrderStatus Status, decimal Total, string? Note);
{"orderId":42,"customer":"Zo\u00EB \u003Czoe@example.com\u003E","status":2,"total":19.99,"note":null}
{"order_id":42,"customer":"Zo\u00EB \u003Czoe@example.com\u003E","status":"in_transit","total":19.99}
{
"order-id": 42,
"customer": "Zoë <zoe@example.com>",
"status": 2,
"total": 19.99,
"note": null
}
Order { OrderId = 7, Customer = Bob, Status = Shipped, Total = 5.50, Note = }
InvalidOperationException
Notes on the options above:
JsonSerializerOptions.Web(.NET 9) has the same defaults ASP.NET Core uses: camelCase property names, case-insensitive property matching on read, and numbers allowed in quotes.new JsonSerializerOptions(JsonSerializerDefaults.Web)does the same and works on older versions. The copy constructornew JsonSerializerOptions(other)starts from existing options.- Naming policies:
CamelCase, and since .NET 8SnakeCaseLower(order_id),SnakeCaseUpper(ORDER_ID),KebabCaseLower(order-id) andKebabCaseUpper. - Enums are written as numbers by default.
JsonStringEnumConverterwrites their names, and can take a naming policy too. DefaultIgnoreCondition:WhenWritingNullskips null properties.WhenWritingDefaultalso skips0,falseand other default values.- Escaping: by default the encoder escapes everything outside ASCII, plus HTML-sensitive characters like
<,>,&and'. That's safe to put into an HTML page but hard to read.JavaScriptEncoder.UnsafeRelaxedJsonEscapingkeeps those characters as they are. It's fine for APIs and files, but don't embed its output in HTML without encoding it. IndentSizeandIndentCharacter(.NET 9) change the indentation.- Reading is case-sensitive by default.
{"orderId": 1}doesn't match propertyOrderIdunless you setPropertyNameCaseInsensitive = trueor use the Web defaults. JsonSerializerOptions.Defaultis the shared default instance. It's read-only, and so is any options instance after its first use.
Attributes
Attributes from System.Text.Json.Serialization let you set the JSON shape for one type without global options:
#:property PublishAot=false
using System.Text.Json;
using System.Text.Json.Serialization;
var u = new User { Id = 1, Email = "a@example.com", PasswordHash = "x9f3", Nickname = null, Role = Role.Admin };
Console.WriteLine(JsonSerializer.Serialize(u));
string ok = """{"user_id": 2, "Email": "b@example.com", "Role": "Editor"}""";
User u2 = JsonSerializer.Deserialize<User>(ok)!;
Console.WriteLine($"{u2.Id} {u2.Email} {u2.Role} created={u2.Created:yyyy}");
foreach (string bad in new[] { """{"Email": "c@example.com"}""", """{"user_id": 3}""" })
{
try
{
JsonSerializer.Deserialize<User>(bad);
}
catch (JsonException e)
{
Console.WriteLine(e.Message);
}
}
enum Role { Viewer, Editor, Admin }
class User
{
[JsonPropertyName("user_id")]
[JsonRequired] // must be present in JSON
public int Id { get; set; }
public required string Email { get; set; } // C# 11 required: enforced by the compiler and by the serializer
[JsonIgnore]
public string? PasswordHash { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? Nickname { get; set; }
[JsonConverter(typeof(JsonStringEnumConverter<Role>))]
[JsonPropertyOrder(-1)] // default order is 0; lower comes first
public Role Role { get; set; }
[JsonInclude] // serialize a property with a private setter
public DateTime Created { get; private set; } = new DateTime(2026, 1, 2);
}
{"Role":"Admin","user_id":1,"Email":"a@example.com","Created":"2026-01-02T00:00:00"}
2 b@example.com Editor created=2026
JSON deserialization for type 'User' was missing required properties including: 'user_id'.
JSON deserialization for type 'User' was missing required properties including: 'Email'.
[JsonPropertyName]sets the JSON name, and it takes priority over the naming policy.[JsonIgnore]never serializes a property. WithCondition = ...it's skipped only when it's null or default.[JsonPropertyOrder]changes the output order. The default is 0, and ties keep declaration order.[JsonConverter]sets a converter for one property or a whole type.JsonStringEnumConverter<TEnum>is the generic, AOT-friendly version.[JsonInclude]serializes non-public setters or public fields.[JsonConstructor]picks a constructor when a type has several.- Required properties:
[JsonRequired]and the C# 11requiredmodifier both make deserialization fail when a property is missing.requiredalso makes the compiler check thatnew User { ... }sets it. A missing property is different from an explicitnull. For null handling, see the strict deserialization section below.
Polymorphism with [JsonDerivedType]
By default the serializer uses the declared type. If a Shape[] holds a Circle, only the properties of Shape are written, and deserializing can't know which subclass to create. Since .NET 7 you list the derived types on the base type, and the serializer writes a type discriminator:
#:property PublishAot=false
using System.Text.Json;
using System.Text.Json.Serialization;
Shape[] shapes = [new Circle(1.5), new Rect(2, 3)];
string json = JsonSerializer.Serialize(shapes);
Console.WriteLine(json);
Shape[] back = JsonSerializer.Deserialize<Shape[]>(json)!;
foreach (var s in back)
Console.WriteLine($"{s.GetType().Name}: area {s.Area():F2}");
try
{
JsonSerializer.Deserialize<Shape>("""{"kind":"triangle","Base":1}""");
}
catch (JsonException e)
{
Console.WriteLine(e.Message);
}
[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]
[JsonDerivedType(typeof(Circle), "circle")]
[JsonDerivedType(typeof(Rect), "rect")]
abstract record Shape
{
public abstract double Area();
}
record Circle(double Radius) : Shape
{
public override double Area() => Math.PI * Radius * Radius;
}
record Rect(double Width, double Height) : Shape
{
public override double Area() => Width * Height;
}
[{"kind":"circle","Radius":1.5},{"kind":"rect","Width":2,"Height":3}]
Circle: area 7.07
Rect: area 6.00
Read unrecognized type discriminator id 'triangle'. Path: $ | LineNumber: 0 | BytePositionInLine: 26.
The discriminator property is called $type by default, and TypeDiscriminatorPropertyName renames it. The id can be a string or an int. Only the listed types are allowed, which is safer than Json.NET's TypeNameHandling, which puts .NET type names into JSON and is a well-known security hole. Before .NET 9 the discriminator had to be the first property in the object. Since .NET 9 AllowOutOfOrderMetadataProperties = true accepts it anywhere.
Custom converters
When the built-in handling doesn't fit, write a JsonConverter<T>. It gets the Utf8JsonReader positioned on the value and must read exactly that value:
#:property PublishAot=false
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
var options = new JsonSerializerOptions { Converters = { new HexColorConverter() } };
var theme = new Theme("dark", new Color(0x1E, 0x1E, 0x2E), new Color(255, 200, 0));
string json = JsonSerializer.Serialize(theme, options);
Console.WriteLine(json);
Console.WriteLine(JsonSerializer.Deserialize<Theme>(json, options));
try { JsonSerializer.Deserialize<Theme>("""{"Name":"x","Background":"red","Accent":"#000000"}""", options); }
catch (JsonException e) { Console.WriteLine(e.Message); }
record struct Color(byte R, byte G, byte B);
record Theme(string Name, Color Background, Color Accent);
// writes Color as "#RRGGBB" instead of {"R":..,"G":..,"B":..}
class HexColorConverter : JsonConverter<Color>
{
public override Color Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
string? s = reader.GetString();
if (s is not { Length: 7 } || s[0] != '#' ||
!uint.TryParse(s.AsSpan(1), NumberStyles.HexNumber, null, out uint rgb))
throw new JsonException($"expected a color like #RRGGBB, got '{s}'");
return new Color((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb);
}
public override void Write(Utf8JsonWriter writer, Color c, JsonSerializerOptions options) =>
writer.WriteStringValue($"#{c.R:X2}{c.G:X2}{c.B:X2}");
}
{"Name":"dark","Background":"#1E1E2E","Accent":"#FFC800"}
Theme { Name = dark, Background = Color { R = 30, G = 30, B = 46 }, Accent = Color { R = 255, G = 200, B = 0 } }
expected a color like #RRGGBB, got 'red'
Throw JsonException for bad input. Register a converter in options.Converters, or put [JsonConverter(typeof(...))] on the type or property. Before writing a converter, check whether an option already does what you need: quoted numbers (NumberHandling), enum names, reference loops (ReferenceHandler.IgnoreCycles), DateOnly/TimeOnly (supported since .NET 7) and Half/Int128 all have built-in support.
JsonNode and JsonDocument
When the JSON has no fixed shape, or you only need a few values from a big document, skip the classes and use the DOM:
using System.Text.Json;
using System.Text.Json.Nodes;
string json = """
{
"name": "build",
"version": 3,
"steps": [
{ "run": "restore", "timeout": 60 },
{ "run": "test", "timeout": 300 }
],
"env": { "CI": "true" }
}
""";
// JsonNode: a mutable DOM
JsonNode root = JsonNode.Parse(json)!;
Console.WriteLine((string)root["name"]!);
Console.WriteLine(root["steps"]![1]!["timeout"]!.GetValue<int>());
Console.WriteLine(root["missing"] is null);
root["version"] = 4;
root["env"]!["DOTNET_NOLOGO"] = "1";
root["steps"]!.AsArray().Add((JsonNode)new JsonObject { ["run"] = "publish", ["timeout"] = 120 });
root.AsObject().Remove("name");
int total = root["steps"]!.AsArray().Sum(s => (int)s!["timeout"]!);
Console.WriteLine($"total timeout: {total}");
Console.WriteLine(root.ToJsonString());
// build a document from scratch
var doc = new JsonObject
{
["id"] = 1,
["tags"] = new JsonArray("a", "b"),
["owner"] = new JsonObject { ["name"] = "Ann" },
};
Console.WriteLine(doc.ToJsonString());
Console.WriteLine(JsonNode.DeepEquals(doc["tags"], JsonNode.Parse("""["a","b"]""")));
// JsonDocument: read-only, faster, uses pooled memory: dispose it
using JsonDocument jd = JsonDocument.Parse(json);
JsonElement steps = jd.RootElement.GetProperty("steps");
Console.WriteLine($"{steps.ValueKind} with {steps.GetArrayLength()} items");
foreach (JsonElement step in steps.EnumerateArray())
Console.WriteLine($" {step.GetProperty("run").GetString()} {step.GetProperty("timeout").GetInt32()}");
if (jd.RootElement.TryGetProperty("env", out JsonElement env))
foreach (JsonProperty p in env.EnumerateObject())
Console.WriteLine($" {p.Name}={p.Value}");
build
300
True
total timeout: 480
{"version":4,"steps":[{"run":"restore","timeout":60},{"run":"test","timeout":300},{"run":"publish","timeout":120}],"env":{"CI":"true","DOTNET_NOLOGO":"1"}}
{"id":1,"tags":["a","b"],"owner":{"name":"Ann"}}
True
Array with 2 items
restore 60
test 300
CI=true
Which one to use:
JsonNode(System.Text.Json.Nodes) is mutable. The indexers returnJsonNode?, so you need!or?.along the path. A missing property returnsnull. Get values with explicit casts ((int)node) orGetValue<T>().ToJsonString()writes the result.JsonNode.DeepEquals(.NET 8) compares two trees.JsonDocumentis read-only and faster. It parses into pooled buffers, so dispose it (using), and don't keep aJsonElementafter the document is disposed. UseGetProperty(throws if missing) orTryGetProperty. CallClone()on an element you want to keep.JsonSerializer.Deserialize<JsonElement>(json)gives you a standaloneJsonElementthat needs no disposing.element.Deserialize<T>()andnode.Deserialize<T>()convert part of a tree into a typed object.
This example has no PublishAot=false line: the DOM types don't use reflection for primitive values, so they work in AOT apps. That's why Add gets a JsonNode argument: the generic Add<T>(T) overload uses reflection and gives an AOT warning.
Utf8JsonWriter and Utf8JsonReader
These are the fastest APIs and use no reflection. Use them for custom converters, for very large inputs, or to write JSON in a fixed format without defining types:
using System.Buffers;
using System.Text;
using System.Text.Json;
// Utf8JsonWriter writes UTF-8 straight to a buffer or stream
var buffer = new ArrayBufferWriter<byte>();
using (var w = new Utf8JsonWriter(buffer, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteString("event", "login");
w.WriteNumber("userId", 42);
w.WriteBoolean("success", true);
w.WriteString("at", new DateTimeOffset(2026, 10, 18, 9, 30, 0, TimeSpan.Zero));
w.WriteStartArray("roles");
w.WriteStringValue("admin");
w.WriteStringValue("dev");
w.WriteEndArray();
w.WriteNull("comment");
w.WriteEndObject();
}
Console.WriteLine(Encoding.UTF8.GetString(buffer.WrittenSpan));
// Utf8JsonReader is a forward-only tokenizer; it's a ref struct, so no async and no lambdas
var reader = new Utf8JsonReader(buffer.WrittenSpan);
while (reader.Read())
{
string value = reader.TokenType switch
{
JsonTokenType.PropertyName or JsonTokenType.String => reader.GetString()!,
JsonTokenType.Number => reader.GetInt32().ToString(),
JsonTokenType.True or JsonTokenType.False => reader.GetBoolean().ToString(),
_ => "",
};
Console.WriteLine($"{reader.TokenType,-12} {value}");
}
// sum one field across a large array without building objects
byte[] data = "[{\"n\":1,\"x\":\"a\"},{\"n\":20},{\"n\":300,\"nested\":{\"n\":9999}}]"u8.ToArray();
var r = new Utf8JsonReader(data);
long sum = 0;
while (r.Read())
{
if (r.TokenType == JsonTokenType.PropertyName && r.CurrentDepth == 2 && r.ValueTextEquals("n"u8))
{
r.Read();
sum += r.GetInt64();
}
}
Console.WriteLine($"sum={sum}");
{
"event": "login",
"userId": 42,
"success": true,
"at": "2026-10-18T09:30:00+00:00",
"roles": [
"admin",
"dev"
],
"comment": null
}
StartObject
PropertyName event
String login
PropertyName userId
Number 42
PropertyName success
True True
PropertyName at
String 2026-10-18T09:30:00+00:00
PropertyName roles
StartArray
String admin
String dev
EndArray
PropertyName comment
Null
EndObject
sum=321
Utf8JsonReader is a ref struct that works on a ReadOnlySpan<byte> (or a ReadOnlySequence<byte>). It can't be used across await or captured in a lambda. ValueTextEquals("n"u8) compares the raw UTF-8 bytes without allocating a string, and CurrentDepth tells you where you are in the tree (the nested "n": 9999 at depth 3 isn't counted). reader.Skip() jumps over a whole object or array. Utf8JsonWriter can also write to a Stream. Dispose or Flush() it before you read the output.
Source generation and Native AOT
Reflection-based serialization inspects your types at run time. That costs startup time, and it doesn't work with trimming or Native AOT, where reflection-based serialization is turned off. The source generator writes the serialization code at compile time instead. You declare a partial class deriving from JsonSerializerContext and list the root types:
using System.Text.Json;
using System.Text.Json.Serialization;
var item = new Product(1, "Keyboard", 49.90m, ["usb", "mechanical"]);
// pass the generated JsonTypeInfo<T>: no reflection, works with trimming and Native AOT
string json = JsonSerializer.Serialize(item, AppJson.Default.Product);
Console.WriteLine(json);
Product back = JsonSerializer.Deserialize(json, AppJson.Default.Product)!;
Console.WriteLine(back.Name);
List<Product> list = JsonSerializer.Deserialize("""[{"id":2,"name":"Mouse","price":19.5,"tags":[]}]""",
AppJson.Default.ListProduct)!;
Console.WriteLine($"{list.Count} {list[0].Name} {list[0].Price}");
// the overload that takes a context and a Type is AOT-safe too
object boxed = new Product(3, "Pad", 5m, []);
Console.WriteLine(JsonSerializer.Serialize(boxed, boxed.GetType(), AppJson.Default));
// AppJson.Default.Options has the settings from [JsonSourceGenerationOptions]
Console.WriteLine(AppJson.Default.Options.PropertyNamingPolicy == JsonNamingPolicy.CamelCase);
// a type that isn't registered in the context fails at run time, not at compile time
try { JsonSerializer.Serialize(DateOnly.MinValue, typeof(DateOnly), AppJson.Default); }
catch (InvalidOperationException e) { Console.WriteLine(e.Message); }
record Product(int Id, string Name, decimal Price, List<string> Tags);
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web, WriteIndented = false)]
[JsonSerializable(typeof(Product))]
[JsonSerializable(typeof(List<Product>))]
partial class AppJson : JsonSerializerContext;
{"id":1,"name":"Keyboard","price":49.90,"tags":["usb","mechanical"]}
Keyboard
1 Mouse 19.5
{"id":3,"name":"Pad","price":5,"tags":[]}
True
JsonTypeInfo metadata for type 'System.DateOnly' was not provided by TypeInfoResolver of type 'AppJson'. If using source generation, ensure that all root types passed to the serializer have been annotated with 'JsonSerializableAttribute', along with any types that might be serialized polymorphically.
This file has no #:property PublishAot=false line. It runs with reflection turned off and compiles without trimming or AOT warnings.
AppJson.Default.Productis a generatedJsonTypeInfo<Product>. Pass it toSerialize/Deserializeinstead of options. Collection types need their own[JsonSerializable].List<Product>becomes the propertyListProduct.[JsonSourceGenerationOptions]sets the options at compile time (here, Web defaults).- Every type you pass as a root must be listed. Types reachable through properties are included automatically. Forgetting one fails at run time, as the
DateOnlyexample shows. - In ASP.NET Core minimal APIs, register the context with
builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJson.Default)). Configuration files shows a context used to save settings.
Even without AOT, the source generator speeds up startup and the first call. It's worth using in any app that serializes a known set of types.
Strict deserialization
The defaults are lenient: unknown properties are ignored, null is accepted for non-nullable reference types, missing constructor parameters get default values, and when a property appears twice the last value wins. .NET 8-10 added options to reject all of these:
#:property PublishAot=false
using System.Text.Json;
using System.Text.Json.Serialization;
string[] inputs =
[
"""{"Host":"db","Port":5432}""",
"""{"Host":"db","Port":5432,"Prot":1}""", // typo: unknown property
"""{"Host":null,"Port":5432}""", // null for non-nullable string
"""{"Host":"db","Host":"evil","Port":5432}""", // duplicate property
"""{"Port":5432}""", // missing constructor parameter
];
Run("default", JsonSerializerOptions.Default);
Run("strict", new JsonSerializerOptions
{
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, // .NET 8
RespectNullableAnnotations = true, // .NET 9
RespectRequiredConstructorParameters = true, // .NET 9
AllowDuplicateProperties = false, // .NET 10
});
Run("Strict preset", JsonSerializerOptions.Strict); // .NET 10: all of the above + case-sensitive
void Run(string label, JsonSerializerOptions options)
{
Console.WriteLine($"--- {label}");
foreach (string json in inputs)
{
try
{
var c = JsonSerializer.Deserialize<DbConfig>(json, options)!;
Console.WriteLine($"ok: Host={c.Host ?? "(null)"} Port={c.Port}");
}
catch (JsonException e)
{
Console.WriteLine($"error: {e.Message.Split(". Path")[0]}");
}
}
}
record DbConfig(string Host, int Port);
--- default
ok: Host=db Port=5432
ok: Host=db Port=5432
ok: Host=(null) Port=5432
ok: Host=evil Port=5432
ok: Host=(null) Port=5432
--- strict
ok: Host=db Port=5432
error: The JSON property 'Prot' could not be mapped to any .NET member contained in type 'DbConfig'.
error: The constructor parameter 'Host' on type 'DbConfig' doesn't allow null values. Consider updating its nullability annotation
error: Duplicate property 'Host' encountered during deserialization of type 'DbConfig'.
error: JSON deserialization for type 'DbConfig' was missing required properties including: 'Host'.
--- Strict preset
ok: Host=db Port=5432
error: The JSON property 'Prot' could not be mapped to any .NET member contained in type 'DbConfig'.
error: The constructor parameter 'Host' on type 'DbConfig' doesn't allow null values. Consider updating its nullability annotation
error: Duplicate property 'Host' encountered during deserialization of type 'DbConfig'.
error: JSON deserialization for type 'DbConfig' was missing required properties including: 'Host'.
UnmappedMemberHandling = Disallow(.NET 8) catches typos and API changes. You can also set it on one type with[JsonUnmappedMemberHandling].RespectNullableAnnotations(.NET 9) uses nullable reference type annotations:stringrejectsnullandstring?allows it. It also checks properties when writing. The project needs<Nullable>enable</Nullable>, which file-based apps and new project templates have by default.RespectRequiredConstructorParameters(.NET 9) makes non-optional constructor parameters required, like[JsonRequired].AllowDuplicateProperties = false(.NET 10) rejects duplicate keys. This matters for security, because different parsers pick different duplicates, and an attacker can use that to get past a validator.JsonSerializerOptions.Strict(.NET 10) turns all of these on, and also makes property matching case-sensitive.
For JSON from outside your program, strict options turn silent data loss into clear errors.
Streams and async
#:property PublishAot=false
using System.Text.Json;
string path = Path.Combine(Path.GetTempPath(), "readings.json");
var readings = Enumerable.Range(1, 5).Select(i => new Reading(i, 20 + i * 0.5)).ToList();
// write to a file stream: no intermediate string
await using (FileStream fs = File.Create(path))
await JsonSerializer.SerializeAsync(fs, readings);
Console.WriteLine(File.ReadAllText(path));
await using (FileStream fs = File.OpenRead(path))
{
var all = await JsonSerializer.DeserializeAsync<List<Reading>>(fs);
Console.WriteLine($"read {all!.Count} readings");
}
// stream a large top-level array one element at a time
await using (FileStream fs = File.OpenRead(path))
{
await foreach (Reading? r in JsonSerializer.DeserializeAsyncEnumerable<Reading>(fs))
{
if (r!.Celsius > 21.5) { Console.WriteLine($"first hot reading: {r}"); break; }
}
}
// JSON Lines (one document per line), .NET 9
string jsonl = "{\"Id\":1,\"Celsius\":3.5}\n{\"Id\":2,\"Celsius\":4.0}\n";
using var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonl));
await foreach (Reading? r in JsonSerializer.DeserializeAsyncEnumerable<Reading>(ms, topLevelValues: true))
Console.WriteLine(r);
File.Delete(path);
record Reading(int Id, double Celsius);
[{"Id":1,"Celsius":20.5},{"Id":2,"Celsius":21},{"Id":3,"Celsius":21.5},{"Id":4,"Celsius":22},{"Id":5,"Celsius":22.5}]
read 5 readings
first hot reading: Reading { Id = 4, Celsius = 22 }
Reading { Id = 1, Celsius = 3.5 }
Reading { Id = 2, Celsius = 4 }
SerializeAsync and DeserializeAsync work on any Stream (files, HTTP bodies, pipes) without loading everything into a string first. DeserializeAsyncEnumerable yields elements of a top-level array as they're parsed, so memory use stays flat for huge files, and breaking out of the loop stops reading. With topLevelValues: true (.NET 9) it reads a sequence of documents separated by whitespace, such as JSON Lines logs. See async/await for await foreach. For HTTP, the System.Net.Http.Json helpers (GetFromJsonAsync<T>, PostAsJsonAsync, ReadFromJsonAsync<T>) wrap these methods. See reading a JSON response and REST APIs.
Tips
- Cache
JsonSerializerOptionsinstances. Creating them per call throws away the metadata cache. - Use
JsonSerializerOptions.Web(or a source-generated context with Web defaults) to match what JavaScript clients and ASP.NET Core expect. - Property names are case-sensitive when reading, unless you use the Web defaults or
PropertyNameCaseInsensitive. - Only properties are serialized, not fields. Use
IncludeFields = trueor[JsonInclude]for fields. - Mark properties
required(or useRespectRequiredConstructorParameters) and turn onRespectNullableAnnotations, so bad input fails at the boundary and not deep in your code. - Use
[JsonDerivedType]for class hierarchies. Never deserialize arbitrary .NET type names from JSON. - Prefer UTF-8 APIs (
SerializeToUtf8Bytes, stream overloads,Utf8JsonReader) on hot paths. - Use source generation for Native AOT, trimmed apps, and fast startup.