← Back to C# Course | Chapter 14: File I/O & Streams | Lesson 6 of 6

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:

  1. Serialization Basics
Syntax
csharp
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

markup
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}");
    }
}
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
  1. Declaring plain public fields on the class and expecting them in the JSON, when System.Text.Json only serializes public properties (with a getter) by default.
  2. Deserializing JSON whose property names differ in case, such as name instead of Name, and getting empty values because matching is case-sensitive unless PropertyNameCaseInsensitive is set.
  3. Using the result of JsonSerializer.Deserialize<Person>(json) without a null check, when it can return null.
Chapter Summary
  • File.ReadAllText and StreamReader and StreamWriter read and write files.
  • Directory, Path, and FileInfo work 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.