System.Text.Json: reading
Reading is the opposite direction: the text arrives from a file, a socket or a command-line argument, and Deserialize maps it to a type. A JSON document does not have to match the type exactly; what is missing becomes the default, what is extra is ignored, and a document that is not JSON throws with a position.
Deserialize a record
The text is written as a raw string literal ("""..."""), so the quotes inside it need no escaping. The property names in the JSON are camelCase and the record parameters are PascalCase, which PropertyNameCaseInsensitive bridges:
using System.Text.Json;
var json = """
{"id":42,"customer":"Ada","lines":[{"sku":"pen","quantity":2,"price":1.50}]}
""";
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var order = JsonSerializer.Deserialize<Order>(json, options)!;
Console.WriteLine($"order {order.Id} {order.Customer}");
Console.WriteLine($"lines {order.Lines.Length}");
Console.WriteLine($"sku {order.Lines[0].Sku} total {order.Lines[0].Quantity * order.Lines[0].Price}");
record Order(int Id, string? Customer, Line[] Lines);
record Line(string Sku, int Quantity, decimal Price);
dotnet run
order 42 Ada
lines 1
sku pen total 3.00
The exclamation mark after the call is the null-forgiving operator: Deserialize returns Order?, because the JSON literal null deserializes to a null reference. A program that does not expect null writes ! and lets a bug surface as a NullReferenceException, or checks the result; a service that accepts untrusted input checks.
A member that is missing
A document with only an id is still a valid order for the serializer. A missing value type becomes its default and a missing reference type becomes null, and no exception is thrown:
using System.Text.Json;
var partial = """{"id":7}""";
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var sparse = JsonSerializer.Deserialize<Order>(partial, options)!;
Console.WriteLine($"sparse customer {sparse.Customer ?? "(null)"}");
Console.WriteLine($"sparse lines {sparse.Lines is null}");
Console.WriteLine($"sparse count {sparse.Lines?.Length ?? -1}");
record Order(int Id, string? Customer, Line[]? Lines);
record Line(string Sku, int Quantity, decimal Price);
dotnet run
sparse customer (null)
sparse lines True
sparse count -1
The nullable annotations on the record say that these two members may be absent, and the program handles both. A record with string Customer and no nullable annotation would still get null there, and the compiler would not warn, because the serializer fills the property after the constructor. That is why a deserialized object needs a check even when its type looks non-nullable.
JsonDocument
When a program needs to look at a document without a type, for example to read one field of a response, JsonDocument parses it into a read-only tree. TryGetProperty answers whether a member exists instead of throwing:
using System.Text.Json;
using var document = JsonDocument.Parse("""{"id":42,"customer":"Ada"}""");
var root = document.RootElement;
Console.WriteLine($"kind {root.ValueKind}");
Console.WriteLine($"has customer {root.TryGetProperty("customer", out var customer)}");
Console.WriteLine($"customer {customer.GetString()}");
Console.WriteLine($"has note {root.TryGetProperty("note", out _)}");
dotnet run
kind Object
has customer True
customer Ada
has note False
ValueKind says what the element is: an object, an array, a string, a number, or one of the literals. A JsonDocument owns its memory and must be disposed, which the using does; for a document that is read once and thrown away, JsonSerializer is shorter.
A document that is not JSON
The comma is missing between the two members, and the parser reports the position of the byte where it noticed. A second failure shows what happens when the text is valid JSON but not the type asked for:
using System.Text.Json;
var bad = """{"id":42 "customer":"Ada"}""";
try
{
JsonSerializer.Deserialize<Order>(bad);
}
catch (JsonException e)
{
Console.WriteLine($"caught {e.GetType().Name}");
Console.WriteLine($"message {e.Message}");
Console.WriteLine($"path {e.Path}");
}
try
{
JsonSerializer.Deserialize<int>("[1,2]");
}
catch (JsonException e)
{
Console.WriteLine($"conversion {e.GetType().Name}");
Console.WriteLine($"inner {e.InnerException?.GetType().Name}");
}
var text = "hello";
Console.WriteLine($"number {JsonSerializer.Deserialize<int>("42")}");
Console.WriteLine($"after {text}");
record Order(int Id, string Customer);
dotnet run
caught JsonException
message '"' is invalid after a value. Expected either ',', '}', or ']'. Path: $ | LineNumber: 0 | BytePositionInLine: 9.
path $
conversion JsonException
inner InvalidOperationException
number 42
after hello
The line number is zero-based and the byte position points at the space where the parser expected a comma; Path is $, the root of the document, because the failure is at the top level. The second call found valid JSON but an array where a number belongs, so it wrapped an InvalidOperationException in a JsonException. Both are caught by the same type, and the program continues to the last two lines.
Exercises
- Deserialize a document with an extra member and confirm that it is ignored.
- Make the missing Customer non-nullable and see whether the compiler warns about the null it gets at run time.
- Read the same text with JsonDocument and with Deserialize and compare the code.
- Break the JSON in three places and compare the line and byte positions of the three exceptions.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which call turns JSON text into an object of a type T?
Answer
JsonSerializer.Deserialize<T>(text)
Deserialize reads and Serialize writes; the type comes as the type argument.
-
What does PropertyNameCaseInsensitive = true allow?
Answer
A JSON member named id to fill a property named Id
It matches member names ignoring case, which bridges camelCase and PascalCase.
-
What does this program print?
using System.Text.Json; Console.WriteLine(JsonSerializer.Deserialize<int[]>("[1,2,3]")!.Length);Answer
3
The array has three elements.
-
What happens to a missing member of reference type during deserialization?
Answer
It stays null and no exception is thrown
The measured sparse document left Customer null.
-
What is a JsonDocument?
Answer
A read-only tree of the parsed document
It parses into elements that a program reads, and it owns the memory it uses.
-
What does this program print?
using System.Text.Json; var d = JsonDocument.Parse("""{"a":1}"""); Console.WriteLine(d.RootElement.GetProperty("a").GetInt32());Answer
1
GetProperty returns the element and GetInt32 reads the number.
-
Which exception does a malformed JSON document throw?
Answer
JsonException
The measured document with a missing comma was caught as JsonException.
-
What does the Path property of a JsonException name?
Answer
The position in the document as a JSONPath
The measured root failure had the path $, the root of the document.
-
What does this program print?
using System.Text.Json; Console.WriteLine(JsonSerializer.Deserialize<int>("42"));Answer
42
A JSON number deserializes to an int and prints without quotes.
-
Why does Deserialize return a nullable result?
Answer
Because the JSON literal null gives a null reference
The literal null is a valid document for a reference type, so the result is nullable.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev