List and dictionary serialization
Learn to serialize List<T> and Dictionary<K,V> to JSON.
Serializing List<T>
JsonSerializer serializes collections, not just single objects. Calling JsonSerializer.Serialize(list) on a List<Person> produces an array: [{...},{...}].
Each element follows the single-object rules. The whole list is wrapped in square brackets. Convert back with Deserialize<List<Person>>(text). This is the easiest way to store multiple records in a file.
Serializing Dictionary<K,V>
A Dictionary<string, int> serializes as key-value pairs: {"apple":5,"pear":3}. The dictionary keys become text; the values are written according to their type.
Convert back with Deserialize<Dictionary<string, int>>(text). Dictionary keys can be string or a number; in serialization they always become text. This is ideal for config or translation tables.
Exercise Serialize a list of Person
Serialize the people list below with JsonSerializer.Serialize(people) and print with Console.WriteLine. The list has two elements.
Show example solution
Convert the list with string text = JsonSerializer.Serialize(people);, print with Console.WriteLine(text);.
Example solution:
using System;
using System.Collections.Generic;
using System.Text.Json;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
var people = new List<Person>
{
new Person { Name = "Alex", Age = 30 },
new Person { Name = "Sam", Age = 25 }
};
string text = JsonSerializer.Serialize(people);
Console.WriteLine(text);
}
}
Test yourself
-
List type parameter
var list = JsonSerializer.Deserialize<List<____>>(text);Show answer
var list = JsonSerializer.Deserialize<List<Person>>(text); -
How is List<Person> serialized?
- As a square-bracketed array
- Like a single object
- As a dictionary
- It cannot be serialized
Show answer
As a square-bracketed array — Correct. List<Person> is serialized as a square-bracketed array: [{...},{...}].
-
Match each type to its output
- List<Person>
- [{...},{...}]
- Dictionary<string,int>
- {"a":1,"b":2}
- Person
- {"Name":"..."}
- int
- 5