π 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
- Return JSON from ASP.NET
Core Controller
csharp
CopyEdit
return Ok(JsonSerializer.Serialize(data));
- Save Object to Local File
csharp
CopyEdit
File.WriteAllText("data.json",
JsonSerializer.Serialize(data));
- 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
Post a Comment