typestar

Deserializing in C#

JSON to a typed record, case-insensitively.

using System.Text.Json;

var json = """{"name": "typestar", "port": 8080, "tags": ["cli", "web"]}""";

var opts = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var server = JsonSerializer.Deserialize<Server>(json, opts);

Console.WriteLine($"{server.Name} on :{server.Port}");
Console.WriteLine(string.Join(",", server.Tags));

// a record's constructor is the deserialization target
record Server(string Name, int Port, string[] Tags);

How it works

  1. Deserialize<Server> maps fields onto the record's constructor.
  2. PropertyNameCaseInsensitive bridges camelCase JSON to PascalCase.
  3. The raw string literal keeps the JSON readable in source.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
456
Tokens
87
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 61 seconds.

Type this snippet

Step 2 of 3 in JSON, step 5 of 17 in The .NET library.

← Previous Next →