C# Programming Tutorial 0/45 lessons ~6 min read Lesson 31

    Serialization

    Serialization converts objects to storable/transmittable formats — binary, XML, JSON.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Serialization converts objects to storable/transmittable formats — binary, XML, JSON. .NET historically used BinaryFormatter (now restricted) and XmlSerializer; modern apps prefer System.Text.Json or Newtonsoft.Json.

    DataContractSerializer, protobuf-net, and MessagePack serve performance-sensitive pipelines. Interviewers ask versioning, circular references, and what fields serialize.

    The story

    A compliance system writes audit events to a message queue as JSON so downstream analytics tools can consume them. Each event includes an ID, action name, and UTC timestamp — serialized with camelCase property names to match JavaScript consumers and a shared JsonSerializerOptions instance for consistent performance.

    Understanding the topic

    Key concepts

    • Serialize object → bytes/text; deserialize reverse.
    • System.Text.Json default in ASP.NET Core.
    • Attributes: JsonPropertyName, JsonIgnore.
    • Records and init properties serialize cleanly.
    • Polymorphic serialization needs type discriminators.
    • Source generators (STJ) for AOT trimming.

    Step-by-step explanation

    1. JsonSerializer.Serialize(obj, options);
    2. Options control naming, indentation, converters.
    3. Deserialize(json) validates structure.
    4. Utf8JsonWriter for low-allocation writing.
    5. Schema evolution: optional new fields ignored on read.
    6. Never deserialize untrusted BinaryFormatter payloads.

    Practical code example

    Serialize audit event with camelCase and source-generated context:

    csharp
    namespace TechLearningPro.Serialization;
    public sealed record AuditEvent(Guid Id, string Action, DateTimeOffset At);
    public static class AuditSerializer
    {
    private static readonly JsonSerializerOptions Options = new()
    {
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    WriteIndented = false
    };
    public static string ToJson(AuditEvent evt) =>
    JsonSerializer.Serialize(evt, Options);
    public static AuditEvent? FromJson(string json) =>
    JsonSerializer.Deserialize<AuditEvent>(json, Options);
    }

    Line-by-line code explanation

    • sealed record AuditEvent(Guid Id, string Action, DateTimeOffset At) is the object being serialized.
    • private static readonly JsonSerializerOptions Options reuses options — creating new options per call is slow.
    • PropertyNamingPolicy = JsonNamingPolicy.CamelCase outputs action instead of Action in JSON.
    • WriteIndented = false produces compact single-line JSON suitable for queues.
    • JsonSerializer.Serialize(evt, Options) converts the record to a JSON string.
    • JsonSerializer.Deserialize<AuditEvent>(json, Options) parses JSON back into a typed object.
    • AuditEvent? return type acknowledges that malformed JSON may yield null.
    • FromJson and ToJson wrap the serializer for call sites that do not need low-level APIs.

    Key takeaway: Reuse JsonSerializerOptions instance — do not create per call. CamelCase matches JavaScript API conventions.

    Real-world use

    Where you'll use this in production

    • REST API JSON request/response bodies.
    • Message queue event payloads.
    • Persisting app state to disk.
    • Caching serialized DTOs in Redis.

    Best practices

    • Use System.Text.Json for new ASP.NET Core projects.
    • Reuse JsonSerializerOptions singleton.
    • Version DTOs; ignore unknown fields on read.
    • Avoid BinaryFormatter entirely.
    • Use source generators for trim/AOT apps.

    Common mistakes

    • Creating new Options every serialization — perf hit.
    • Serializing entity navigation graphs — cycles.
    • Deserializing untrusted types — security risk.
    • Mismatch property names without JsonPropertyName.

    Advanced interview questions

    Q1BeginnerJSON serializer in ASP.NET Core?
    System.Text.Json by default; Newtonsoft optional.
    Q2BeginnerJsonIgnore purpose?
    Exclude property from serialization.
    Q3IntermediateHandle polymorphic JSON?
    JsonDerivedType attributes or custom converter with type discriminator.
    Q4IntermediateBinaryFormatter why deprecated?
    Remote code execution risk deserializing untrusted data.
    Q5AdvancedDesign backward-compatible event schema evolution.
    Add optional fields; never rename/remove without version bump; consumers ignore unknown; use $schema version field.

    Summary

    Serialization persists and transmits object state. System.Text.Json is the modern default. Configure options once; handle schema evolution. Never use BinaryFormatter on untrusted input. Next: JSON handling in depth.

    Ready to mark this lesson complete?Track your journey across the entire course.