CommunityProgramación y desarrollogithub.com

serialización

Elige el formato de serialización adecuado para aplicaciones .NET. Prefiere formatos basados en esquemas (Protobuf, MessagePack) sobre los basados en reflexión (Newtonsoft.Json). Usa System.Text.Json con generadores de código fuente AOT para escenarios JSON.

¿Qué es serialización?

Esta habilidad proporciona una guía completa para seleccionar e implementar la serialización en aplicaciones .NET, priorizando formatos basados en esquemas como Protocol Buffers y MessagePack sobre enfoques basados en reflexión como Newtonsoft.Json. Es especialmente útil para desarrolladores que trabajan con APIs, sistemas de mensajería entre actores, event sourcing o cualquier escenario que cruce límites de procesos, ya que ofrece recomendaciones claras sobre qué formato usar según el caso de uso (REST, gRPC, caching, logging, etc.) y explica por qué ciertos formatos como BinaryFormatter deben evitarse por completo. La habilidad cubre en detalle System.Text.Json con generadores de código fuente para compatibilidad AOT, incluyendo ejemplos de configuración, uso en ASP.NET Core y migración desde Newtonsoft.Json. También aborda la serialización con Protocol Buffers (incluyendo reglas de versionado) y MessagePack con soporte AOT, así como patrones de compatibilidad en el cable como el "Tolerent Reader" y "Introducir Lectura Antes que Escritura". Además, incluye una comparación de rendimiento entre formatos y mejores prácticas concretas, con ejemplos de código en C# que muestran tanto lo que se debe hacer como lo que se debe evitar.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/serialization

Installed? Explore more Programación y desarrollo skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Serialización en .NET

Cuándo Usar Esta Habilidad

Usa esta habilidad cuando:

  • Estés eligiendo un formato de serialización para APIs, mensajería o persistencia
  • Estés migrando de Newtonsoft.Json a System.Text.Json
  • Estés implementando serialización compatible con AOT
  • Estés diseñando formatos de cable para sistemas distribuidos
  • Estés optimizando el rendimiento de la serialización

Basado en Esquemas vs Basado en Reflexión

AspectoBasado en EsquemasBasado en Reflexión
EjemplosProtobuf, MessagePack, System.Text.Json (source gen)Newtonsoft.Json, BinaryFormatter
Información de tipo en el payloadNo (esquema externo)Sí (nombres de tipo incrustados)
VersionadoNúmeros/nombres de campo explícitosImplícito (estructura de tipo)
RendimientoRápido (sin reflexión)Más lento (reflexión en tiempo de ejecución)
Compatible con AOTSíNo
Compatibilidad en cableExcelentePobre

Recomendación: Usa serialización basada en esquemas para todo lo que cruce límites de procesos.


Recomendaciones de Formatos

Caso de UsoFormato RecomendadoPor Qué
APIs RESTSystem.Text.Json (source gen)Estándar, compatible con AOT
gRPCProtocol BuffersFormato nativo, excelente versionado
Mensajería entre actoresMessagePack o ProtobufCompacto, rápido, seguro para versiones
Event sourcingProtobuf o MessagePackDebe manejar eventos antiguos para siempre
CachingMessagePackCompacto, rápido
ConfiguraciónJSON (System.Text.Json)Legible por humanos
Registro (logging)JSON (System.Text.Json)Estructurado, analizable

Formatos a Evitar

FormatoProblema
BinaryFormatterVulnerabilidades de seguridad, obsoleto, nunca usar
Newtonsoft.Json por defectoNombres de tipo en el payload se rompen al renombrar
DataContractSerializerComplejo, pobre versionado
XMLVerboso, lento, complejo

System.Text.Json con Generadores de Código Fuente

Para serialización JSON, usa System.Text.Json con generadores de código fuente para compatibilidad AOT y rendimiento.

Configuración

// Define un JsonSerializerContext con todos tus tipos
[JsonSerializable(typeof(Order))]
[JsonSerializable(typeof(OrderItem))]
[JsonSerializable(typeof(Customer))]
[JsonSerializable(typeof(List<Order>))]
[JsonSourceGenerationOptions(
    PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
public partial class AppJsonContext : JsonSerializerContext { }

Uso

// Serializar con contexto
var json = JsonSerializer.Serialize(order, AppJsonContext.Default.Order);

// Deserializar con contexto
var order = JsonSerializer.Deserialize(json, AppJsonContext.Default.Order);

// Configurar en ASP.NET Core
builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default);
});

Beneficios

  • Sin reflexión en tiempo de ejecución - Toda la información de tipo se genera en tiempo de compilación
  • Compatible con AOT - Funciona con publicación Native AOT
  • Más rápido - Sin análisis de tipo en tiempo de ejecución
  • Seguro para el enlazador - El enlazador sabe exactamente qué se necesita

Protocol Buffers (Protobuf)

Mejor para: Sistemas de actores, gRPC, event sourcing, cualquier formato de cable de larga duración.

Configuración

dotnet add package Google.Protobuf
dotnet add package Grpc.Tools

Definir Esquema

// orders.proto
syntax = "proto3";

message Order {
    string id = 1;
    string customer_id = 2;
    repeated OrderItem items = 3;
    int64 created_at_ticks = 4;

    // Agregar nuevos campos siempre es seguro
    string notes = 5;  // Agregado en v2 - los lectores antiguos lo ignoran
}

message OrderItem {
    string product_id = 1;
    int32 quantity = 2;
    int64 price_cents = 3;
}

Reglas de Versionado

// SEGURO: Agregar nuevos campos con nuevos números
message Order {
    string id = 1;
    string customer_id = 2;
    string shipping_address = 5;  // NUEVO - seguro
}

// SEGURO: Eliminar campos (lectores antiguos ignoran desconocidos, nuevos usan valor por defecto)
// Simplemente deja de usar el campo, mantén el número reservado
message Order {
    string id = 1;
    // customer_id eliminado, pero el campo 2 está reservado
    reserved 2;
}

// NO SEGURO: Cambiar tipos de campo
message Order {
    int32 id = 1;  // Era: string - ¡SE ROMPE!
}

// NO SEGURO: Reutilizar números de campo
message Order {
    reserved 2;
    string new_field = 2;  // Reutilizando 2 - ¡SE ROMPE!
}

MessagePack

Mejor para: Escenarios de alto rendimiento, payloads compactos, mensajería entre actores.

Configuración

dotnet add package MessagePack
dotnet add package MessagePack.Annotations

Uso con Contratos

[MessagePackObject]
public sealed class Order
{
    [Key(0)]
    public required string Id { get; init; }

    [Key(1)]
    public required string CustomerId { get; init; }

    [Key(2)]
    public required IReadOnlyList<OrderItem> Items { get; init; }

    [Key(3)]
    public required DateTimeOffset CreatedAt { get; init; }

    // Nuevo campo - lectores antiguos omiten claves desconocidas
    [Key(4)]
    public string? Notes { get; init; }
}

// Serializar
var bytes = MessagePackSerializer.Serialize(order);

// Deserializar
var order = MessagePackSerializer.Deserialize<Order>(bytes);

Configuración Compatible con AOT

// Usa generador de código fuente para AOT
[MessagePackObject]
public partial class Order { }  // partial habilita source gen

// Configurar resolver
var options = MessagePackSerializerOptions.Standard
    .WithResolver(CompositeResolver.Create(
        GeneratedResolver.Instance,  // Generado
        StandardResolver.Instance));

Migrando desde Newtonsoft.Json

Problemas Comunes

NewtonsoftSystem.Text.JsonSolución
$type en JSONNo soportado por defectoUsa discriminadores o convertidores personalizados
JsonPropertyJsonPropertyNameAtributo diferente
DefaultValueHandlingDefaultIgnoreConditionAPI diferente
NullValueHandlingDefaultIgnoreConditionAPI diferente
Setters privadosRequiere [JsonInclude]Opt-in explícito
Polimorfismo[JsonDerivedType] (.NET 7+)Discriminadores explícitos

Patrón de Migración

// Newtonsoft (basado en reflexión)
public class Order
{
    [JsonProperty("order_id")]
    public string Id { get; set; }

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string? Notes { get; set; }
}

// System.Text.Json (compatible con source-gen)
public sealed record Order(
    [property: JsonPropertyName("order_id")]
    string Id,

    string? Notes  // Manejo de nulos via JsonSerializerOptions
);

[JsonSerializable(typeof(Order))]
[JsonSourceGenerationOptions(
    PropertyNamingPolicy = JsonKnownNamingPolicy.SnakeCaseLower,
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
public partial class OrderJsonContext : JsonSerializerContext { }

Polimorfismo con Discriminadores

// Polimorfismo .NET 7+
[JsonDerivedType(typeof(CreditCardPayment), "credit_card")]
[JsonDerivedType(typeof(BankTransferPayment), "bank_transfer")]
public abstract record Payment(decimal Amount);

public sealed record CreditCardPayment(decimal Amount, string Last4) : Payment(Amount);
public sealed record BankTransferPayment(decimal Amount, string AccountNumber) : Payment(Amount);

// Se serializa como:
// { "$type": "credit_card", "amount": 100, "last4": "1234" }

Patrones de Compatibilidad en Cable

Lector Tolerante

El código antiguo debe ignorar de forma segura campos desconocidos:

// Protobuf/MessagePack: Automático - campos desconocidos se omiten
// System.Text.Json: Configurar para permitir
var options = new JsonSerializerOptions
{
    UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip
};

Introducir Lectura Antes que Escritura

Despliega deserializadores antes que serializadores para nuevos formatos:

// Fase 1: Agregar deserializador (desplegado en todas partes)
public Order Deserialize(byte[] data, string manifest) => manifest switch
{
    "Order.V1" => DeserializeV1(data),
    "Order.V2" => DeserializeV2(data),  // NUEVO - puede leer V2
    _ => throw new NotSupportedException()
};

// Fase 2: Habilitar serializador (siguiente versión, después de que V1 esté en todas partes)
public (byte[] data, string manifest) Serialize(Order order) =>
    _useV2Format
        ? (SerializeV2(order), "Order.V2")
        : (SerializeV1(order), "Order.V1");

Nunca Incrustar Nombres de Tipo

// MAL: Nombre de tipo en el payload - renombrar clase rompe el formato de cable
{
    "$type": "MyApp.Order, MyApp.Core",
    "id": "123"
}

// BIEN: Discriminador explícito - seguro para refactorización
{
    "type": "order",
    "id": "123"
}

Comparación de Rendimiento

Throughput aproximado (más alto es mejor):

FormatoSerializarDeserializarTamaño
MessagePack★★★★★★★★★★★★★★★
Protobuf★★★★★★★★★★★★★★★
System.Text.Json (source gen)★★★★☆★★★★☆★★★☆☆
System.Text.Json (reflexión)★★★☆☆★★★☆☆★★★☆☆
Newtonsoft.Json★★☆☆☆★★☆☆☆★★★☆☆

Para caminos críticos, prefiere MessagePack o Protobuf.


Serialización en Akka.NET

Para sistemas de actores Akka.NET, usa serialización basada en esquemas:

akka {
  actor {
    serializers {
      messagepack = "Akka.Serialization.MessagePackSerializer, Akka.Serialization.MessagePack"
    }
    serialization-bindings {
      "MyApp.Messages.IMessage, MyApp" = messagepack
    }
  }
}

Ver Documentación de Serialización de Akka.NET.


Mejores Prácticas

HACER

// Usa generadores de código fuente para System.Text.Json
[JsonSerializable(typeof(Order))]
public partial class AppJsonContext : JsonSerializerContext { }

// Usa números/claves de campo explícitos
[MessagePackObject]
public class Order
{
    [Key(0)] public string Id { get; init; }
}

// Usa registros para tipos de mensajes inmutables
public sealed record OrderCreated(OrderId Id, CustomerId CustomerId);

NO HACER

// No uses BinaryFormatter (nunca)
var formatter = new BinaryFormatter();  // ¡Riesgo de seguridad!

// No incrustes nombres de tipo en el formato de cable
settings.TypeNameHandling = TypeNameHandling.All;  // ¡Se rompe al renombrar!

// No uses serialización por reflexión para caminos críticos
JsonConvert.SerializeObject(order);  // Lento, no compatible con AOT

Recursos

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

Skills relacionados