Serialization
Serialization converts objects to storable/transmittable formats — binary, XML, JSON.
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
- JsonSerializer.Serialize(obj, options);
- Options control naming, indentation, converters.
- Deserialize
(json) validates structure. - Utf8JsonWriter for low-allocation writing.
- Schema evolution: optional new fields ignored on read.
- Never deserialize untrusted BinaryFormatter payloads.
Practical code example
Serialize audit event with camelCase and source-generated context:
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 Optionsreuses options — creating new options per call is slow.PropertyNamingPolicy = JsonNamingPolicy.CamelCaseoutputsactioninstead ofActionin JSON.WriteIndented = falseproduces 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.FromJsonandToJsonwrap 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?
Q2BeginnerJsonIgnore purpose?
Q3IntermediateHandle polymorphic JSON?
Q4IntermediateBinaryFormatter why deprecated?
Q5AdvancedDesign backward-compatible event schema evolution.
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.