JsonSerializer basics
Learn to convert objects to JSON with JsonSerializer.
What is serialization?
Serialization turns an object into text so it can be saved to a file or sent over a network. In C# the JsonSerializer class from the System.Text.Json namespace does this job.
Call: string text = JsonSerializer.Serialize(obj);. The return value is a string; the object's properties are written as key-value pairs. For example new Person { Name = "Alex", Age = 30 } produces {"Name":"Alex","Age":30}. The reverse operation is Deserialize.
The System.Text.Json namespace
To use JsonSerializer, add using System.Text.Json; at the top. This namespace is .NET's built-in serializer; no external package is needed.
A class is serializable by default: public properties are processed automatically. A property like public string Name { get; set; } becomes the pair "Name":"value". private members are not serialized.
Exercise Serialize a Person object
The Person class below is ready. In Main create a Person instance (Name = "Alex", Age = 30), convert it to text with JsonSerializer.Serialize and print with Console.WriteLine.
Show example solution
Create the instance with var p = new Person { Name = "Alex", Age = 30 };, convert with string text = JsonSerializer.Serialize(p);, print with Console.WriteLine(text);.
Example solution:
using System;
using System.Text.Json;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
var p = new Person { Name = "Alex", Age = 30 };
string text = JsonSerializer.Serialize(p);
Console.WriteLine(text);
}
}
Test yourself
-
What does Serialize return?
JsonSerializer.Serialize(p)- string
- Person
- byte[]
- void
Show answer
string — Correct. Serialize returns the text representation of the object as a string.
-
Complete the Serialize call
string text = JsonSerializer.____(p);Show answer
string text = JsonSerializer.Serialize(p); -
Match each method to its role
- Serialize
- Object to text
- Deserialize
- Text to object
- JsonSerializer
- Class name
- System.Text.Json
- Namespace