πŸ”„ Serialization in .NET Core: A Developer’s Guide

 

Serialization is one of those core programming concepts that quietly powers a huge part of modern applications — from APIs and caching to message queues and local storage.

In .NET Core, you have several powerful tools for serialization, each with different strengths and use cases.


πŸ“¦ What Is Serialization?

Serialization is the process of converting an object into a format that can be stored or transmitted — like JSON, XML, or binary.

The reverse process is deserialization — reconstructing the object from the serialized format.


πŸ“š Common Use Cases

  • πŸ“‘ Sending data over APIs (JSON/XML)
  • 🧠 Caching objects in memory or Redis
  • πŸ’Ύ Saving to disk (config/settings)
  • πŸ“€ Message queues and event publishing
  • πŸ”’ Encrypting/decrypting structured data

⚙️ Built-in Serializers in .NET Core

Serializer

Format

Best For

System.Text.Json

JSON

Fast, modern, built-in JSON

Newtonsoft.Json

JSON

Advanced JSON features

XmlSerializer

XML

Interop, config files

BinaryFormatter ⚠️

Binary

Obsolete (security risks)

DataContractSerializer

XML

WCF/Interop scenarios


πŸ”§ System.Text.Json (Default in .NET Core)

Fast and native to .NET Core (from .NET Core 3.0+).

Serialize an Object to JSON

csharp

CopyEdit

using System.Text.Json;

 

var person = new Person { Name = "Ali", Age = 30 };

string json = JsonSerializer.Serialize(person);

πŸ” Deserialize JSON to Object

csharp

CopyEdit

var deserialized = JsonSerializer.Deserialize<Person>(json);

⚙️ Custom Options

csharp

CopyEdit

var options = new JsonSerializerOptions

{

    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,

    WriteIndented = true

};

 

string formattedJson = JsonSerializer.Serialize(person, options);


πŸ” Newtonsoft.Json (Json.NET)

More flexible and widely used in legacy apps or complex scenarios.

Setup

Install via NuGet:

bash

CopyEdit

dotnet add package Newtonsoft.Json

Usage

csharp

CopyEdit

using Newtonsoft.Json;

 

string json = JsonConvert.SerializeObject(person);

var personObj = JsonConvert.DeserializeObject<Person>(json);

πŸ”„ Advantages Over System.Text.Json

  • Full support for polymorphism
  • Attributes like [JsonIgnore], [JsonProperty("alias")]
  • Custom converters
  • Better handling of circular references

πŸ“„ XML Serialization

Basic XML Serializer

csharp

CopyEdit

using System.Xml.Serialization;

using System.IO;

 

var serializer = new XmlSerializer(typeof(Person));

using var writer = new StringWriter();

serializer.Serialize(writer, person);

string xml = writer.ToString();

Deserialization

csharp

CopyEdit

using var reader = new StringReader(xml);

var personFromXml = (Person)serializer.Deserialize(reader);


⚠️ BinaryFormatter Is Obsolete

BinaryFormatter was used to serialize objects into compact binary form, but it is not secure and should not be used in modern apps.

Use System.Text.Json, MessagePack, or protobuf-net instead.


πŸ“¦ Advanced Serialization Scenarios

Ignore Properties

csharp

CopyEdit

public class Person

{

    public string Name { get; set; }

 

    [JsonIgnore] // For System.Text.Json

    public int Age { get; set; }

}

Custom Naming

csharp

CopyEdit

[JsonPropertyName("full_name")]

public string Name { get; set; }


πŸš€ Real-World Examples

  1. Return JSON from ASP.NET Core Controller

csharp

CopyEdit

return Ok(JsonSerializer.Serialize(data));

  1. Save Object to Local File

csharp

CopyEdit

File.WriteAllText("data.json", JsonSerializer.Serialize(data));

  1. Deserialize JSON from Web API

csharp

CopyEdit

var json = await httpClient.GetStringAsync("https://api");

var result = JsonSerializer.Deserialize<MyDto>(json);


πŸ’‘ Best Practices

  • Use System.Text.Json for most apps for performance.
  • Use Newtonsoft.Json if you need advanced scenarios.
  • Avoid BinaryFormatter; prefer safer formats.
  • Always validate external input before deserialization.
  • Keep DTOs flat and clean for simpler (de)serialization.

πŸ”š Summary

Feature

Recommendation

Speed + Lightweight

System.Text.Json

Complex JSON scenarios

Newtonsoft.Json

Legacy XML support

XmlSerializer

Avoided for security

BinaryFormatter

 

Comments

Popular posts from this blog

Scrutor the built-in Dependency Injection (DI)

πŸ§… Understanding the Onion Architecture: A Clean Approach to Building Scalable Applications

πŸ”Œ Extension Methods in C#: Power Up Your Code Without Modifying It

Understanding Dependency Injection: A Modern Guide for Developers

🌐 CORS in .NET Explained: Solving the Cross-Origin Problem Like a Pro

Ensuring Data Integrity: The Backbone of Reliable Systems

πŸ” JWT (JSON Web Token) Explained: Secure Your APIs the Modern Way

πŸ”— SQL JOINs Explained: Mastering Table Relationships

πŸ—‚️ DROP vs DELETE vs TRUNCATE in SQL: What’s the Difference?

πŸ›‘️ SIEM Logs Explained: How to Build Secure and Auditable .NET Apps