Serialization Basics
Serialization is packing an object flat like a boxed puzzle so it can be saved or sent, and then rebuilt later. It turns your data into text or bytes that can travel.
In this page:
Syntax
using System.Text.Json;
string json = JsonSerializer.Serialize(objectValue);
ClassName obj = JsonSerializer.Deserialize<ClassName>(json);
Serialization Basics
Serialization converts an object into a storable or transmittable format, like JSON, and deserialization reverses the process.
System.Text.Json provides JsonSerializer.Serialize and JsonSerializer.Deserialize for this in modern .NET. This is the standard way to save structured data to a file or send it over a network.
Note:
Public properties (not fields) are what
System.Text.Json serializes by default.Example: Serialization Basics
using System;
using System.Text.Json;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Person p = new Person { Name = "Nina", Age = 27 };
string json = JsonSerializer.Serialize(p);
Console.WriteLine(json);
Person restored = JsonSerializer.Deserialize<Person>(json);
Console.WriteLine($"{restored.Name}, {restored.Age}");
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Declaring plain public fields on the class and expecting them in the JSON, when
System.Text.Jsononly serializes public properties (with a getter) by default. - Deserializing JSON whose property names differ in case, such as
nameinstead ofName, and getting empty values because matching is case-sensitive unlessPropertyNameCaseInsensitiveis set. - Using the result of
JsonSerializer.Deserialize<Person>(json)without a null check, when it can returnnull.
Chapter Summary
File.ReadAllTextandStreamReaderandStreamWriterread and write files.Directory,Path, andFileInfowork with folders, paths, and file details.- Serialization basics turn objects into stored data.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: