Serialization in .NET
When to Use This Skill
Use this skill when:
- Choosing a serialization format for APIs, messaging, or persistence
- Migrating from Newtonsoft.Json to System.Text.Json
- Implementing AOT-compatible serialization
- Designing wire formats for distributed systems
- Optimizing serialization performance
Schema-Based vs Reflection-Based
Recommendation: Use schema-based serialization for anything that crosses process boundaries.
Format Recommendations
Formats to Avoid
System.Text.Json with Source Generators
For JSON serialization, use System.Text.Json with source generators for AOT compatibility and performance.
Setup
Usage
Benefits
- No reflection at runtime - All type info generated at compile time
- AOT compatible - Works with Native AOT publishing
- Faster - No runtime type analysis
- Trim-safe - Linker knows exactly what's needed
Protocol Buffers (Protobuf)
Best for: Actor systems, gRPC, event sourcing, any long-lived wire format.
Setup
Define Schema
Versioning Rules
MessagePack
Best for: High-performance scenarios, compact payloads, actor messaging.
Setup
Usage with Contracts
AOT-Compatible Setup
Migrating from Newtonsoft.Json
Common Issues
Migration Pattern
Polymorphism with Discriminators
Wire Compatibility Patterns
Tolerant Reader
Old code must safely ignore unknown fields:
Introduce Read Before Write
Deploy deserializers before serializers for new formats:
Never Embed Type Names
Performance Comparison
Approximate throughput (higher is better):
For hot paths, prefer MessagePack or Protobuf.
Akka.NET Serialization
For Akka.NET actor systems, use schema-based serialization:
See Akka.NET Serialization Docs.
Best Practices
DO
DON'T
Resources
- System.Text.Json Source Generation: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/source-generation
- Protocol Buffers: https://protobuf.dev/
- MessagePack-CSharp: https://github.com/MessagePack-CSharp/MessagePack-CSharp
- Akka.NET Serialization: https://getakka.net/articles/networking/serialization.html
- Wire Compatibility: https://getakka.net/community/contributing/wire-compatibility.html


