← Open in the full interactive course (progress tracking, search & more)

JSON is one answer to a much older question: how do you turn a living object in memory into something that can survive being written down?

You just spent a whole lesson on JSON — converting objects to text and back. But JSON is really just one specific answer to a much broader problem that software has faced since long before JSON existed: an object in memory disappears the moment your program stops running or the moment it needs to leave that one process. How do you turn it into something that can be written to disk, sent across a network, or handed to a completely different system — and later turned back into a usable object again?

That general problem — and its family of solutions — is called serialization. JSON is one format for it. XML is another, older one, still very much alive in plenty of real systems. Binary formats are a third family, optimized differently again. In this lesson, you'll get a first-look, conceptual tour of serialization as a whole — what it is, why it exists, and how to think about choosing between JSON, XML, and binary formats.

What Is It?

The Simple Explanation

Serialization is the general process of converting a "live" object — sitting in your program's memory, with all its structure and relationships — into a flat sequence of data (usually text or bytes) that can be stored or transmitted. Deserialization is reversing that: taking the stored/transmitted data and rebuilding an equivalent object from it.

The Technical Definition

Serialization is the process of translating an in-memory data structure or object state into a format that can be persisted (written to storage) or transmitted (sent across a boundary such as a network connection) and later reconstructed. The chosen format — JSON, XML, a binary protocol, and others — determines the rules for how that translation happens: how types are represented, how much space it takes, whether a human can read the result directly, and how strict the structure needs to be.

Why Does It Exist?

The Problem

An object living in your program's memory is tied entirely to that one running process — its exact memory layout, its pointers to other objects, its runtime type information. None of that survives the process ending, and none of it means anything to a different program, a different machine, or a file on disk. Yet real systems constantly need objects to outlive a single process, or to travel somewhere else entirely: saved to disk, sent to another service, cached, queued for later processing.

The Need

What's needed is a standard, repeatable way to "flatten" an object's state into something portable — and to reliably reconstruct it later, possibly in a different process, on a different machine, even written in a different language.

The Solution — A Family of Serialization Formats

Different formats trade off readability, size, speed, and interoperability differently — which is exactly why more than one continues to matter in practice, rather than everyone simply converging on a single "best" choice.

Big Picture

The same order object, expressed in three different serialization formats:

FormatWhat it looks like
JSON {"orderId":1042,"customerName":"Acme Co","total":149.99}
XML <Order><OrderId>1042</OrderId><CustomerName>Acme Co</CustomerName><Total>149.99</Total></Order>
Binary 01 04 12 0A 00 00 41 63 6D 65 20 43 6F ... (raw bytes — not meant to be read by a human at all)
CHOOSING A FORMAT — THE TRADE-OFFS
JSON
Compact, readable, near-universal language support. Today's default for web APIs.
XML
Verbose but rigorously structured — schemas, validation, namespaces. Common in enterprise/legacy systems.
Binary
Smallest, fastest, not human-readable. Ideal when both ends are known and speed/size really matter.

How It Works

Regardless of the specific format, serialization always follows the same conceptual shape:

THE SERIALIZATION LIFECYCLE
Step 1 — You have a live object in memory
Step 2 — Serialize: flatten it into the chosen format
Step 3 — Store or transmit the result
Step 4 — Deserialize: reconstruct the object, wherever it's needed

Simple Example

The same object, serialized to both JSON (which you already know from the previous lesson) and XML, using .NET's respective built-in serializers:

public class Order { public int OrderId { get; set; } public string CustomerName { get; set; } = ""; public decimal Total { get; set; } } var order = new Order { OrderId = 1042, CustomerName = "Acme Co", Total = 149.99m }; // ─── JSON, via System.Text.Json ─── string json = JsonSerializer.Serialize(order); Console.WriteLine(json); // {"OrderId":1042,"CustomerName":"Acme Co","Total":149.99} // ─── XML, via System.Xml.Serialization ─── var xmlSerializer = new XmlSerializer(typeof(Order)); using var stringWriter = new StringWriter(); xmlSerializer.Serialize(stringWriter, order); Console.WriteLine(stringWriter.ToString()); // <?xml version="1.0" encoding="utf-16"?> // <Order> // <OrderId>1042</OrderId> // <CustomerName>Acme Co</CustomerName> // <Total>149.99</Total> // </Order>

Same object, same information — two structurally different representations, each following that format's own rules and conventions. Notice how much more verbose the XML version is for the exact same data; that verbosity buys XML things JSON doesn't emphasize as strongly, like namespaces, attributes, and mature schema-validation tooling — which is why XML remains common in domains (finance, healthcare, many enterprise and government systems) that value rigorous, formally validated document structure.

Real-World Example

A realistic scenario many enterprise developers eventually run into: a modern order-processing service needs to send new orders to a long-standing partner system that only understands XML, while its own internal event log (read only by its own services) uses JSON:

public class OrderIntegrationService { // Legacy partner's B2B integration only accepts XML — a common real-world constraint public string BuildPartnerXmlPayload(Order order) { var serializer = new XmlSerializer(typeof(Order)); using var writer = new StringWriter(); serializer.Serialize(writer, order); return writer.ToString(); } // Our own internal event log — JSON is simpler and everything internal already speaks it public string BuildInternalEventJson(Order order) { var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; return JsonSerializer.Serialize(new { eventType = "OrderCreated", order, loggedAtUtc = DateTimeOffset.UtcNow }, options); } } // ─── Usage ─── var service = new OrderIntegrationService(); var order = new Order { OrderId = 1042, CustomerName = "Acme Co", Total = 149.99m }; SendToPartnerSystem(service.BuildPartnerXmlPayload(order)); // the partner's legacy system expects XML AppendToInternalLog(service.BuildInternalEventJson(order)); // our own tooling expects JSON

This is exactly the kind of situation where knowing serialization as a general concept — not just "how JSON works" — pays off: the same underlying Order object needs to speak two completely different "languages" depending on who's listening, and .NET's built-in serializers make that a matter of picking the right tool, not reinventing anything from scratch.

Under the Hood

At this first-look level, the important thing to internalize is why binary formats are so much smaller and faster than text-based ones like JSON and XML. Text formats spend bytes on things a human needs to read them — punctuation, field names repeated in every single object, whitespace for readability. A binary format typically skips all of that: numbers are stored as raw bytes rather than as decimal-digit characters, and field identity is often implied by position or a compact numeric code rather than a repeated text name.

The trade-off, in one sentence: Text formats (JSON, XML) spend extra size and speed to stay human-readable and easy to debug; binary formats spend readability to gain size and speed. Neither is "better" in the abstract — the right choice depends entirely on who (or what) needs to read the data, and how much size and speed actually matter for that specific use case.

Common Confusion

1. "Serialization" and "JSON" are not the same thing

After the previous lesson, it's easy to start using these interchangeably — but JSON is just one format serialization can target. Saying "serialize the order" doesn't, by itself, say which format is meant; "serialize the order to JSON" or "serialize the order to XML" is the complete, unambiguous statement.

2. "XML is obsolete, nobody should use it anymore"

JSON has clearly displaced XML as the default for new web APIs — but plenty of established enterprise systems, financial messaging standards, document formats (including, ironically, the raw format underlying modern .docx/.xlsx files), and configuration formats still use XML, often because of its mature support for formal schemas and validation. Knowing it exists and roughly how it compares is genuinely useful, not purely historical trivia.

Common Mistakes

Mistake 1 — Choosing a format out of habit rather than fit

Defaulting to JSON for absolutely everything, including a scenario where the actual consumer of the data is a legacy system that only understands XML, or a very high-throughput internal channel where a compact binary format would meaningfully reduce size and processing time. The format should fit the actual consumer and constraints, not just "whatever's most familiar."

Mistake 2 — Assuming a binary format is human-inspectable for debugging

Reaching for a binary serialization format for a scenario where developers regularly need to open the raw output and read it directly while debugging. Binary output isn't meant to be read by eye at all — if human readability during troubleshooting genuinely matters, that's a strong point in favor of a text format like JSON, even at some cost in size and speed.

Mistake 3 — Treating "serialization" and "the JSON I already know" as the same skill

Assuming that because you know JsonSerializer, you've fully learned "serialization" as a concept, and being caught off guard by an XML- or binary-based system later. The underlying idea — flatten a live object into portable data, then rebuild it later — transfers across every format; only the specific API and its output conventions actually change.

When Should I Use It?

JSON
Web APIs, config, most new inter-service communication — the modern default.
XML
Legacy/enterprise integrations, formats requiring formal schema validation.
Binary
Performance- or size-critical paths where both ends are known and control the format.
Ask first
Who reads this data, how often, how fast, and does a human ever need to read it directly?
Rule of thumb: Default to JSON unless you have a specific, concrete reason not to — an existing system that requires XML, or a genuine, measured performance/size need that justifies a binary format. Most everyday applications never need anything beyond JSON.

Mental Model

Serialization = the general act of flattening a live object into portable data.
JSON, XML, binary = specific formats — each a different set of trade-offs, not competing "winners."
Text formats trade size/speed for human readability. Binary formats trade readability for size/speed.

Remember:
· "Serialize" always needs a format in mind — it's a category, not one specific technology.
· JSON is the modern default; XML persists where formal schemas/legacy integration matter; binary shines under real performance constraints.
· The right format is determined by who reads the data and what actually matters for that exchange — not by habit.

Key Takeaway


Check Your Understanding

You've taken a broader look at serialization as a concept, beyond just JSON. Let's check your understanding.

1. What is the relationship between "serialization" and "JSON"?

Show answer

Correct: B

Why B is correct: Serialization is the general process — flattening a live object into portable data and reconstructing it later. JSON is one specific format that process can target; XML and various binary formats are others. "Serialize" always implies a chosen format, even when that format goes unstated.

Why A is incorrect: This conflates the general concept with one specific implementation of it — exactly the confusion the lesson calls out directly.

Why C is incorrect: This reverses the actual relationship — JSON is the narrower, specific format; serialization is the broader concept encompassing it and others.

Why D is incorrect: Serialization applies to any format — text-based (JSON, XML) and binary formats are all valid targets of serialization, not just binary ones.

Reinforcement: Serialization is the category; JSON, XML, and binary formats are members of that category, each with different trade-offs.

2. Why is XML output typically much larger than JSON output for the exact same data?

Show answer

Correct: B

Why B is correct: XML wraps every value in a matching opening and closing tag (like <CustomerName>...</CustomerName>), which repeats the field name twice per value. JSON represents the same relationship more compactly with a single key followed by a colon and the value. That structural difference is exactly why the same data produces noticeably more XML text than JSON text.

Why A is incorrect: XML doesn't apply any compression by default — its larger size comes from its more verbose tag-based syntax, not from a compression step gone wrong.

Why C is incorrect: XML can represent the same range of data types as JSON (through text representations) — this isn't a data-type limitation causing the size difference.

Why D is incorrect: Both JSON and XML are text-based formats — neither is inherently binary; the size difference comes from their differing text syntax, not from one being binary.

Reinforcement: XML's opening/closing tag syntax is inherently more verbose than JSON's key-value punctuation for representing the same structure.

3. A high-frequency internal service needs to exchange millions of small messages per second between two components you fully control, where no human ever needs to read the raw messages directly. Based on the lesson's trade-off discussion, which format characteristic matters most here?

Show answer

Correct: B

Why B is correct: This scenario — extremely high message volume, both ends controlled internally, no need for humans to read raw messages — is exactly the profile where trading away human readability for size and speed pays off, making a binary format a strong fit based on the trade-offs discussed in the lesson.

Why A is incorrect: The scenario explicitly states no human needs to read the raw messages — readability isn't a relevant requirement here, so it shouldn't drive the format choice.

Why C is incorrect: XML isn't required for high-frequency exchanges — if anything, its verbosity works against the stated goals of minimizing size and maximizing speed in this scenario.

Why D is incorrect: Format choice does affect performance — text formats carry real parsing and size overhead compared to binary formats, which is precisely why the trade-off exists and matters at scale.

Reinforcement: Match the format to the actual constraints of the exchange — this scenario's lack of a human-readability need combined with extreme volume favors binary's size/speed trade-off.

4. In the OrderIntegrationService example, why does the same Order object get serialized to two different formats (XML for the partner system, JSON for the internal event log) rather than picking just one format for everything?

Show answer

Correct: B

Why B is correct: This models a very real situation — different consumers of the same data can have different, fixed format requirements. The service picks the format that matches each specific recipient's actual needs, rather than forcing one universal choice that wouldn't work for both.

Why A is incorrect: The same object can be serialized to as many different formats as needed, using separate serializer calls — there's no such one-format-per-object restriction.

Why C is incorrect: XML isn't universally required for outbound data — the internal event log in the very same example uses JSON, showing the choice is consumer-specific, not a blanket rule.

Why D is incorrect: JSON represents decimal values just fine (as seen throughout the previous lesson's examples) — that's not the reason XML is used for the partner integration.

Reinforcement: The right serialization format is determined by what the actual consumer of the data requires, and different consumers can reasonably require different formats.

5. Why is it a mistake to assume that fully understanding System.Text.Json means you've fully learned "serialization" as a concept?

Show answer

Correct: B

Why B is correct: Knowing JSON serialization deeply gives you the general mental model (flatten an object, reconstruct it later) but not the specific APIs, quirks, or conventions of other formats like XML or binary serialization. The underlying idea transfers, but the concrete tools and rules differ per format — that's exactly why the lesson frames serialization as the broader category and JSON as one member of it.

Why A is incorrect: JsonSerializer.Serialize and Deserialize are genuine, complete implementations of serialization for the JSON format — they perform real, correct serialization, just for one specific format.

Why C is incorrect: System.Text.Json is an actively maintained, current part of .NET — there's no indication it's being removed, and that isn't the reasoning behind this mistake anyway.

Why D is incorrect: JSON serialization handles full object graphs — nested objects, lists, records — not just primitive types, as shown throughout the previous lesson.

Reinforcement: The concept of serialization transfers across formats, but the specific tools and conventions for each format still need to be learned individually.

That completes this module on errors, files, and dates — you now understand exceptions and custom exception types, file and directory operations, safe path handling, a working knowledge of streams, unambiguous date/time handling with time zones, and serialization both broadly and through JSON specifically. Together, these are the everyday building blocks behind almost every real .NET application.


dotnetmadeeasy.com — Learn C# and .NET, the right way.