C# Tutorial: JSON Encoding
Serialize and deserialize JSON with System.Text.Json, custom converters, and JsonNode in C#.
System.Text.Json
Built-in since .NET 3.0 — no extra packages needed:
```csharp
using System.Text.Json;
```
---
Serialize (Object → JSON)
```csharp
var user = new { Name = "Alice", Age = 30, Tags = new[] { "dev", "cs" } };
string json = JsonSerializer.Serialize(user);
Console.WriteLine(json);
// {"Name":"Alice","Age":30,"Tags":["dev","cs"]}
// Pretty-print
string pretty = JsonSerializer.Serialize(user,
new JsonSerializerOptions { WriteIndented = true });
```
---
Deserialize (JSON → Object)
Define a class matching your JSON:
```csharp
class Post {
public int Id { get; set; }
public string Title { get; set; } = "";
public string Body { get; set; } = "";
}
string json = """{"id":1,"title":"Hello","body":"World"}""";
var post = JsonSerializer.Deserialize<Post>(json,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
Console.WriteLine(post?.Title); // Hello
```
---
JsonSerializerOptions
```csharp
var options = new JsonSerializerOptions {
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // Name → name
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
```
---
Attributes
```csharp
class Product {
[JsonPropertyName("product_name")]
public string Name { get; set; } = "";
[JsonIgnore]
public string InternalCode { get; set; } = "";
}
```
---
Dynamic JSON with JsonNode (C# 6+)
When you don't know the schema:
```csharp
var node = JsonNode.Parse(json);
string? title = node?["title"]?.GetValue<string>();
```
---
Streams (Memory-Efficient)
```csharp
using var stream = File.OpenRead("data.json");
var data = await JsonSerializer.DeserializeAsync<List<Post>>(stream);
```
---
What's Next?
You can work with any JSON API or file. Next: **switch expressions and pattern matching** — advanced control flow, type patterns, and property patterns.
What you'll learn in this C# json encoding tutorial
This interactive C# tutorial has 5 hands-on exercises. Estimated time: 10 minutes.
- Serialize to JSON — Create an anonymous object `{ Name = "Alice", Age = 30 }` and serialize it to JSON with `JsonSerializer.Serialize`. Prin…
- Deserialize from JSON — Define `record User(string Name, int Age)`. Deserialize `{"Name":"Bob","Age":25}` and print the `Name`.
- Case-Insensitive Options — Deserialize `{"name":"Carol","age":22}` (lowercase keys) into a `User` record using `PropertyNameCaseInsensitive = true`…
- JsonPropertyName Attribute — Define a class `Product` where the JSON key is `"product_name"` but the C# property is `Name`. Deserialize `{"product_na…
- Pretty Print — Serialize `{ Title = "Hello", Views = 100 }` with `WriteIndented = true` and print just the first line of the output (wh…
C# JSON Encoding concepts covered
- System.Text.Json
- Serialize (Object → JSON)
- Deserialize (JSON → Object)
- JsonSerializerOptions
- Attributes
- Dynamic JSON with JsonNode (C# 6+)
- Streams (Memory-Efficient)
- What's Next?