Codectionary / Developer documentation / C#

System.Text.Json Serialization

JsonSerializer converts .NET values to and from JSON. Typed deserialization provides structure but application-specific validation remains the caller’s responsibility. Use a .NET 8+ console project; replace Program.cs with this C# example.

Read the syntax

JsonSerializer converts .NET values to and from JSON. Typed deserialization provides structure but application-specific validation remains the caller’s responsibility. Use a .NET 8+ console project; replace Program.cs with this C# example.

The array round-trips through JSON. Deserialization may return null for the JSON value null, so this example supplies an empty-array fallback.

Syntax

JsonSerializer.Serialize(value); JsonSerializer.Deserialize<T>(json)

Examples

System.Text.Json Serialization

Use a .NET 8+ console project; replace Program.cs with this C# example.

using System;
using System.Text.Json;
var counts = new int[] { 2, 4, 6 };
string json = JsonSerializer.Serialize(counts);
int[] restored = JsonSerializer.Deserialize<int[]>(json) ?? Array.Empty<int>();
Console.WriteLine(json);
Console.WriteLine(restored[1]);
  1. Expected output: [2,4,6] 4
  2. The array round-trips through JSON. Deserialization may return null for the JSON value null, so this example supplies an empty-array fallback.
  3. Validate shape, length and domain constraints after parsing.

Best practices

  • Validate shape, length and domain constraints after parsing.
  • Use shared JsonSerializerOptions when applying a consistent naming policy.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading