C# JSON
last modified November 15, 2026
This C# JSON tutorial shows how to work with JSON data using the
System.Text.Json namespace of the standard library. We parse JSON
documents, serialize and deserialize objects, build and modify JSON, read and
write JSON at the token level, and fetch JSON from the web.
JSON
JSON (JavaScript Object Notation) is a lightweight format for data exchange. It
is easy for humans to read and write and easy for machines to parse and
generate. The official Internet media type for JSON is
application/json, and JSON files use the .json
extension. JSON supports strings, numbers, booleans, null, arrays, and objects,
which can be nested to represent complex data structures.
In this tutorial, we work with the JSON support built into .NET. There is also
a widely used third-party library called Json.NET
(Newtonsoft.Json). System.Text.Json is recommended for new
projects because of its performance and integration with .NET, while
Json.NET remains common in older code bases.
System.Text.Json
The System.Text.Json namespace provides a high-performance,
standards-compliant JSON implementation that works directly with UTF-8 data.
It is part of .NET since .NET Core 3.0. It offers several APIs:
JsonSerializer- converts between objects and JSON text,JsonDocument- a fast read-only document object model,JsonNode- a mutable document object model,Utf8JsonReaderandUtf8JsonWriter- low-level, forward-only token APIs.
The examples use a regular console project created with dotnet new
console; files such as data.json are created in the project
directory.
C# JSON parse
The JsonDocument.Parse method parses JSON text into a
JsonDocument. The document gives read-only access to the data
through JsonElement values. This is useful when we need to inspect
JSON data without mapping it to C# types.
using System.Text.Json;
string data = """
[
{ "name": "John Doe", "occupation": "gardener", "age": 34 },
{ "name": "Peter Novak", "occupation": "driver", "age": 41 }
]
""";
using JsonDocument doc = JsonDocument.Parse(data);
JsonElement root = doc.RootElement;
Console.WriteLine(root.ValueKind);
Console.WriteLine(root.GetArrayLength());
JsonElement u1 = root[0];
Console.WriteLine(u1);
string? name = u1.GetProperty("name").GetString();
int age = u1.GetProperty("age").GetInt32();
Console.WriteLine($"{name} is {age} years old");
if (!u1.TryGetProperty("email", out JsonElement email))
{
Console.WriteLine("no email property");
}
In the example, we parse a JSON array of two user objects and read some of their values.
using JsonDocument doc = JsonDocument.Parse(data); JsonElement root = doc.RootElement;
We parse the string and get the root element with the
RootElement property. JsonDocument uses pooled
memory, so it should be disposed; hence the using
declaration.
Console.WriteLine(root.ValueKind); Console.WriteLine(root.GetArrayLength());
The ValueKind property tells the type of the JSON value. The root
is an array and GetArrayLength returns its number of elements.
string? name = u1.GetProperty("name").GetString();
int age = u1.GetProperty("age").GetInt32();
The indexer returns an array element and GetProperty returns the
value of an object property. Methods such as GetString and
GetInt32 convert the value to a .NET type.
if (!u1.TryGetProperty("email", out JsonElement email))
GetProperty throws a KeyNotFoundException for a
missing property; TryGetProperty returns false
instead.
$ dotnet run
Array
2
{ "name": "John Doe", "occupation": "gardener", "age": 34 }
John Doe is 34 years old
no email property
C# JSON enumerate
The EnumerateArray method iterates over the elements of a JSON
array and the EnumerateObject method over the properties of a
JSON object.
using System.Text.Json;
string data = """
[
{ "name": "John Doe", "occupation": "gardener", "age": 34 },
{ "name": "Peter Novak", "occupation": "driver", "age": 41 }
]
""";
using var doc = JsonDocument.Parse(data);
JsonElement root = doc.RootElement;
foreach (JsonElement user in root.EnumerateArray())
{
foreach (JsonProperty prop in user.EnumerateObject())
{
Console.WriteLine($"{prop.Name}: {prop.Value} ({prop.Value.ValueKind})");
}
Console.WriteLine("--------------------");
}
int total = root.EnumerateArray().Sum(u => u.GetProperty("age").GetInt32());
Console.WriteLine($"total age: {total}");
We go over all users and print their properties with the kinds of their values.
foreach (JsonElement user in root.EnumerateArray())
{
foreach (JsonProperty prop in user.EnumerateObject())
The enumerators work with foreach. A JsonProperty
has a Name and a Value.
int total = root.EnumerateArray().Sum(u => u.GetProperty("age").GetInt32());
The enumerators implement IEnumerable, so they can be used with
LINQ.
$ dotnet run name: John Doe (String) occupation: gardener (String) age: 34 (Number) -------------------- name: Peter Novak (String) occupation: driver (String) age: 41 (Number) -------------------- total age: 75
C# JSON serialize
The JsonSerializer.Serialize method converts an object into a JSON
string. Serialization is used when sending data to web APIs or saving data to
files.
using System.Text.Json;
var user = new User("John Doe", "gardener", new DateOnly(1995, 11, 30),
["gardening", "chess"]);
string json = JsonSerializer.Serialize(user);
Console.WriteLine(json);
List<User> users =
[
user,
new User("Roger Roe", "driver", new DateOnly(1987, 3, 12), [])
];
Console.WriteLine(JsonSerializer.Serialize(users));
record User(string Name, string Occupation, DateOnly DateOfBirth, string[] Hobbies);
In the example, we serialize a User record and a list of users.
string json = JsonSerializer.Serialize(user);
The serializer writes all public properties. By default, the property names are used as they are, and the output is compact, without whitespace.
The DateOnly value is written as an ISO 8601 date string, the
array as a JSON array, and the list of records as an array of objects.
$ dotnet run
{"Name":"John Doe","Occupation":"gardener","DateOfBirth":"1995-11-30","Hobbies":["gardening","chess"]}
[{"Name":"John Doe","Occupation":"gardener","DateOfBirth":"1995-11-30","Hobbies":["gardening","chess"]},{"Name":"Roger Roe","Occupation":"driver","DateOfBirth":"1987-03-12","Hobbies":[]}]
C# JSON deserialize
The JsonSerializer.Deserialize method parses JSON text into an
instance of the specified type. We get strongly-typed C# objects to work
with.
using System.Text.Json;
string json = """
{
"name": "John Doe",
"occupation": "gardener",
"dateOfBirth": "1995-11-30",
"hobbies": ["gardening", "chess"]
}
""";
var user = JsonSerializer.Deserialize<User>(json);
Console.WriteLine(user?.Name ?? "(null)");
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
user = JsonSerializer.Deserialize<User>(json, options);
Console.WriteLine(user);
Console.WriteLine(user?.DateOfBirth.Year);
Console.WriteLine(string.Join(", ", user?.Hobbies ?? []));
class User
{
public string? Name { get; set; }
public string? Occupation { get; set; }
public DateOnly DateOfBirth { get; set; }
public List<string> Hobbies { get; set; } = [];
public override string ToString() => $"{Name}, {Occupation}, {DateOfBirth}";
}
The example parses a JSON object into an instance of the User
class.
var user = JsonSerializer.Deserialize<User>(json); Console.WriteLine(user?.Name ?? "(null)");
By default, property names are matched case-sensitively. The JSON uses
name, the class Name, so nothing matches and the
properties keep their default values. Unknown properties are ignored without
an error.
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
user = JsonSerializer.Deserialize<User>(json, options);
With case-insensitive matching, all properties are filled. The date string is
converted to DateOnly and the array to a list.
$ dotnet run (null) John Doe, gardener, 11/30/1995 1995 gardening, chess
C# JsonSerializerOptions
The JsonSerializerOptions class controls the serialization: the
indentation, the naming of properties, the handling of null values, the
conversion of enums, and more.
using System.Text.Json;
using System.Text.Json.Serialization;
var product = new Product("Wireless mouse", 24.99m, Category.Electronics, null);
var options = new JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Converters = { new JsonStringEnumConverter() }
};
string json = JsonSerializer.Serialize(product, options);
Console.WriteLine(json);
var webJson = JsonSerializer.Serialize(product, JsonSerializerOptions.Web);
Console.WriteLine(webJson);
record Product(string ProductName, decimal UnitPrice, Category Category,
string? Description);
enum Category { Books, Electronics, Garden }
We serialize a product with custom options and with the web defaults.
WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
WriteIndented enables pretty printing. The naming policy
converts ProductName to product_name; other policies
include CamelCase, SnakeCaseUpper, and
KebabCaseLower.
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Converters = { new JsonStringEnumConverter() }
Properties with null values are skipped. The
JsonStringEnumConverter writes enum values as names instead of
numbers.
var webJson = JsonSerializer.Serialize(product, JsonSerializerOptions.Web);
The JsonSerializerOptions.Web instance holds the defaults used by
ASP.NET Core: camel-case names, case-insensitive reading, and numbers allowed
in strings. Without the converter, the enum is written as the number 1.
$ dotnet run
{
"product_name": "Wireless mouse",
"unit_price": 24.99,
"category": "Electronics"
}
{"productName":"Wireless mouse","unitPrice":24.99,"category":1,"description":null}
Serialization attributes
Attributes from the System.Text.Json.Serialization namespace
customize the serialization of individual properties.
using System.Text.Json;
using System.Text.Json.Serialization;
var account = new Account
{
Id = 1,
UserName = "jdoe",
Password = "s3cret",
Created = new DateTime(2026, 1, 15, 10, 30, 0)
};
string json = JsonSerializer.Serialize(account);
Console.WriteLine(json);
var copy = JsonSerializer.Deserialize<Account>(json);
Console.WriteLine($"{copy?.UserName}, password: {copy?.Password ?? "(not set)"}");
class Account
{
[JsonPropertyName("account_id")]
public int Id { get; set; }
[JsonPropertyName("user")]
public string UserName { get; set; } = "";
[JsonIgnore]
public string? Password { get; set; }
[JsonPropertyOrder(-1)]
public DateTime Created { get; set; }
}
We serialize an account with renamed, ignored, and reordered properties.
[JsonPropertyName("account_id")]
public int Id { get; set; }
The JsonPropertyName attribute sets the name used in JSON, both
for writing and reading.
[JsonIgnore]
public string? Password { get; set; }
The JsonIgnore attribute excludes the property from
serialization and deserialization. The password does not appear in the JSON
and is not set when the JSON is read back.
[JsonPropertyOrder(-1)]
Properties are written in declaration order. The
JsonPropertyOrder attribute changes the position; the default
order value is 0, so -1 moves the property to the front.
$ dotnet run
{"Created":"2026-01-15T10:30:00","account_id":1,"user":"jdoe"}
jdoe, password: (not set)
C# JsonNode
JsonDocument is read-only. When we need to modify JSON without
defining classes, we use JsonNode and its subclasses
JsonObject, JsonArray, and
JsonValue.
using System.Text.Json;
using System.Text.Json.Nodes;
string data = """
{ "name": "John Doe", "occupation": "gardener", "skills": ["pruning"] }
""";
JsonNode node = JsonNode.Parse(data)!;
Console.WriteLine((string?) node["name"]);
node["occupation"] = "landscaper";
node["age"] = 34;
node["skills"]!.AsArray().Add("planting");
node.AsObject().Remove("name");
var address = new JsonObject
{
["city"] = "Bratislava",
["zip"] = "81101"
};
node["address"] = address;
var options = new JsonSerializerOptions { WriteIndented = true };
Console.WriteLine(node.ToJsonString(options));
The example parses a JSON object, changes it, and prints the result.
Console.WriteLine((string?) node["name"]);
The indexer returns a child node. An explicit cast converts a value node to a .NET type.
node["occupation"] = "landscaper";
node["age"] = 34;
node["skills"]!.AsArray().Add("planting");
node.AsObject().Remove("name");
We replace a value, add a new property, append an element to an array, and
remove a property. Strings and numbers are implicitly converted to
JsonNode values.
var address = new JsonObject
{
["city"] = "Bratislava",
["zip"] = "81101"
};
A JsonObject can be built with an object initializer and
attached to another node.
$ dotnet run
John Doe
{
"occupation": "landscaper",
"skills": [
"pruning",
"planting"
],
"age": 34,
"address": {
"city": "Bratislava",
"zip": "81101"
}
}
C# Utf8JsonWriter
The Utf8JsonWriter class provides a high-performance,
forward-only API for writing UTF-8 encoded JSON. It gives full control over
the output without creating intermediate objects.
using System.Text;
using System.Text.Json;
using var ms = new MemoryStream();
using (var writer = new Utf8JsonWriter(ms))
{
writer.WriteStartObject();
writer.WriteString("name", "John Doe");
writer.WriteString("occupation", "gardener");
writer.WriteNumber("age", 34);
writer.WriteStartArray("languages");
writer.WriteStringValue("English");
writer.WriteStringValue("Slovak");
writer.WriteEndArray();
writer.WriteEndObject();
}
string json = Encoding.UTF8.GetString(ms.ToArray());
Console.WriteLine(json);
In the example, we write a JSON object with an array into a memory stream.
writer.WriteStartObject();
writer.WriteString("name", "John Doe");
We write the start of an object and then the properties one by one. Every start must be paired with an end call.
writer.WriteStartArray("languages");
writer.WriteStringValue("English");
Inside an array, values are written without names.
string json = Encoding.UTF8.GetString(ms.ToArray());
The writer is disposed at the end of the using block, which
flushes its buffer to the stream. Then we decode the UTF-8 bytes into a
string.
$ dotnet run
{"name":"John Doe","occupation":"gardener","age":34,"languages":["English","Slovak"]}
Writing JSON to a file
The JsonDocument.WriteTo method writes a document to a
Utf8JsonWriter. With the Indented option of
JsonWriterOptions, the output is pretty printed.
using System.Text.Json;
string data = """
[ { "name": "John Doe", "occupation": "gardener", "age": 34 },
{ "name": "Peter Novak", "occupation": "driver", "age": 41 } ]
""";
using JsonDocument doc = JsonDocument.Parse(data);
var fileName = "data.json";
using (FileStream fs = File.Create(fileName))
using (var writer = new Utf8JsonWriter(fs, new JsonWriterOptions { Indented = true }))
{
doc.WriteTo(writer);
}
Console.WriteLine(File.ReadAllText(fileName));
In the example, we parse a JSON string and write it to the
data.json file.
using (FileStream fs = File.Create(fileName))
using (var writer = new Utf8JsonWriter(fs, new JsonWriterOptions { Indented = true }))
File.Create truncates an existing file, so a shorter document
never leaves old data at the end of the file. The writer writes directly to
the file stream.
$ dotnet run
[
{
"name": "John Doe",
"occupation": "gardener",
"age": 34
},
{
"name": "Peter Novak",
"occupation": "driver",
"age": 41
}
]
C# Utf8JsonReader
The Utf8JsonReader struct reads JSON token by token. It is the
fastest way to process JSON and the basis of the other APIs.
using System.Text.Json;
byte[] data = File.ReadAllBytes("data.json");
var reader = new Utf8JsonReader(data);
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonTokenType.StartObject:
Console.WriteLine("-------------");
break;
case JsonTokenType.PropertyName:
Console.Write($"{reader.GetString()}: ");
break;
case JsonTokenType.String:
Console.WriteLine(reader.GetString());
break;
case JsonTokenType.Number:
Console.WriteLine(reader.GetInt32());
break;
}
}
Console.WriteLine($"{reader.BytesConsumed} bytes consumed");
In the example, we read the data.json file created in the
previous section.
byte[] data = File.ReadAllBytes("data.json");
var reader = new Utf8JsonReader(data);
The reader works over UTF-8 bytes, so we read the file as bytes.
while (reader.Read())
{
switch (reader.TokenType)
The Read method moves to the next token and returns
false at the end of the data. The TokenType property
tells what kind of token we are on. Tokens which the switch does not handle,
such as the end of an object, are skipped.
case JsonTokenType.Number:
Console.WriteLine(reader.GetInt32());
break;
The value of a number token is read with one of the typed methods.
$ dotnet run ------------- name: John Doe occupation: gardener age: 34 ------------- name: Peter Novak occupation: driver age: 41 157 bytes consumed
Serializing to files asynchronously
The SerializeAsync and DeserializeAsync methods
write JSON to a stream and read it from a stream. They do not need the whole
JSON text as a string in memory.
using System.Text.Json;
List<TodoItem> items =
[
new("Write report", 2, false),
new("Fix bug #42", 1, true),
new("Plan sprint", 3, false)
];
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
WriteIndented = true
};
var fileName = "tasks.json";
await using (FileStream fs = File.Create(fileName))
{
await JsonSerializer.SerializeAsync(fs, items, options);
}
Console.WriteLine(File.ReadAllText(fileName));
await using FileStream input = File.OpenRead(fileName);
var loaded = await JsonSerializer.DeserializeAsync<List<TodoItem>>(input, options);
foreach (var item in loaded ?? [])
{
Console.WriteLine(item);
}
record TodoItem(string Title, int Priority, bool Done);
We save a list of to-do items to a file and load it back.
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
WriteIndented = true
};
We start from the web defaults and turn on indentation. The same options must be used for writing and reading, so that the camel-case names match.
await JsonSerializer.SerializeAsync(fs, items, options);
The list is written to the file stream.
var loaded = await JsonSerializer.DeserializeAsync<List<TodoItem>>(input, options);
The records are created through their constructors; the JSON names are matched to the constructor parameters.
$ dotnet run
[
{
"title": "Write report",
"priority": 2,
"done": false
},
{
"title": "Fix bug #42",
"priority": 1,
"done": true
},
{
"title": "Plan sprint",
"priority": 3,
"done": false
}
]
TodoItem { Title = Write report, Priority = 2, Done = False }
TodoItem { Title = Fix bug #42, Priority = 1, Done = True }
TodoItem { Title = Plan sprint, Priority = 3, Done = False }
C# JSON parse async
The JsonDocument.ParseAsync method parses JSON from a stream
asynchronously. Combined with HttpClient, it reads JSON from the
network.
using System.Text.Json;
using var client = new HttpClient();
var url = "https://builds.dotnet.microsoft.com/dotnet/release-metadata/releases-index.json";
await using Stream stream = await client.GetStreamAsync(url);
using JsonDocument doc = await JsonDocument.ParseAsync(stream);
JsonElement releases = doc.RootElement.GetProperty("releases-index");
foreach (JsonElement release in releases.EnumerateArray().Take(5))
{
string? version = release.GetProperty("channel-version").GetString();
string? latest = release.GetProperty("latest-release").GetString();
string? phase = release.GetProperty("support-phase").GetString();
Console.WriteLine($"{version,-5} {latest,-8} {phase}");
}
The example reads the index of .NET releases, which Microsoft publishes as a JSON file, and prints the five newest versions with their support status.
await using Stream stream = await client.GetStreamAsync(url); using JsonDocument doc = await JsonDocument.ParseAsync(stream);
We get the response body as a stream and parse it.
JsonElement releases = doc.RootElement.GetProperty("releases-index");
The releases are in the releases-index array of the root object.
The output reflects the state of the index on the day the program runs.
$ dotnet run 11.0 11.0.0 active 10.0 10.0.15 active 9.0 9.0.23 eol 8.0 8.0.34 eol 7.0 7.0.20 eol
C# HttpClient GetFromJsonAsync
The GetFromJsonAsync extension method from the
System.Net.Http.Json namespace sends a GET request and
deserializes the response body. It uses the web defaults of
JsonSerializerOptions.
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using var client = new HttpClient();
var url = "https://builds.dotnet.microsoft.com/dotnet/release-metadata/releases-index.json";
var index = await client.GetFromJsonAsync<ReleaseIndex>(url);
var lts = index?.Releases.Where(r => r.ReleaseType == "lts").Take(4) ?? [];
foreach (var release in lts)
{
Console.WriteLine(release);
}
record ReleaseIndex(
[property: JsonPropertyName("releases-index")] List<Release> Releases);
record Release(
[property: JsonPropertyName("channel-version")] string ChannelVersion,
[property: JsonPropertyName("latest-release")] string LatestRelease,
[property: JsonPropertyName("release-type")] string ReleaseType,
[property: JsonPropertyName("eol-date")] DateOnly? EolDate);
We read the same release index into records and print the long-term support (LTS) releases.
var index = await client.GetFromJsonAsync<ReleaseIndex>(url);
The method sends the request, checks the status code, and deserializes the JSON in one call.
record Release(
[property: JsonPropertyName("channel-version")] string ChannelVersion,
[property: JsonPropertyName("latest-release")] string LatestRelease,
[property: JsonPropertyName("release-type")] string ReleaseType,
[property: JsonPropertyName("eol-date")] DateOnly? EolDate);
The JSON names contain hyphens, so we map them with the
JsonPropertyName attribute. The property: target
applies the attribute to the generated property of the positional record. We
only declare the properties we need; the rest of the JSON is ignored.
$ dotnet run
Release { ChannelVersion = 10.0, LatestRelease = 10.0.15, ReleaseType = lts, EolDate = 11/14/2028 }
Release { ChannelVersion = 8.0, LatestRelease = 8.0.34, ReleaseType = lts, EolDate = 11/10/2026 }
Release { ChannelVersion = 6.0, LatestRelease = 6.0.36, ReleaseType = lts, EolDate = 11/12/2024 }
Release { ChannelVersion = 3.1, LatestRelease = 3.1.32, ReleaseType = lts, EolDate = 12/13/2022 }
Source generation
By default, JsonSerializer inspects types with reflection at
runtime. With source generation, the serialization code is generated at
compile time. This speeds up startup and is required for Native AOT and
trimmed applications.
using System.Text.Json;
using System.Text.Json.Serialization;
var user = new User("John Doe", "gardener", 34);
string json = JsonSerializer.Serialize(user, AppJsonContext.Default.User);
Console.WriteLine(json);
User? copy = JsonSerializer.Deserialize(json, AppJsonContext.Default.User);
Console.WriteLine(copy);
record User(string Name, string Occupation, int Age);
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(User))]
partial class AppJsonContext : JsonSerializerContext;
The example serializes a record with a source-generated context.
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] [JsonSerializable(typeof(User))] partial class AppJsonContext : JsonSerializerContext;
We declare a partial class derived from JsonSerializerContext and
list the types to serialize. The source generator fills in the rest of the
class. Options set in the attribute are compiled in.
string json = JsonSerializer.Serialize(user, AppJsonContext.Default.User);
The generated User property holds the type information, which we
pass to the serializer instead of relying on reflection.
$ dotnet run
{"name":"John Doe","occupation":"gardener","age":34}
User { Name = John Doe, Occupation = gardener, Age = 34 }
Source
JSON serialization and deserialization in .NET
Use a JSON document object model
Source generation in System.Text.Json
In this article we have worked with JSON data in C#. We have parsed JSON with
JsonDocument and JsonNode, serialized and
deserialized objects, used options and attributes, worked with the reader and
writer, and read JSON from the web. See also the C#
YAML and C# HttpClient articles.
Author
List all C# tutorials.