Community编程与开发github.com

序列化

为.NET应用程序选择合适的序列化格式。推荐基于模式的格式(Protobuf、MessagePack)而非基于反射的格式(Newtonsoft.Json)。对于JSON场景,使用System.Text.Json和AOT源代码生成器。

序列化 是什么?

该技能提供了在.NET应用程序中选择和实现序列化格式的全面指南。它强调在进程边界通信时使用基于模式的序列化(如Protobuf、MessagePack和System.Text.Json的源代码生成器),而不是基于反射的格式(如Newtonsoft.Json),因为后者会嵌入类型信息、性能较慢且不兼容AOT。技能详细比较了各种格式,为REST API、gRPC、Actor消息传递、事件溯源、缓存、配置和日志记录提供了具体推荐,并明确警告不要使用BinaryFormatter、Newtonsoft.Json的默认设置、DataContractSerializer和XML。它包含了使用System.Text.Json源代码生成器实现AOT兼容JSON序列化的实际代码示例,以及Protobuf和MessagePack的用法和版本控制规则。此外,还提供了从Newtonsoft.Json迁移的模式、处理多态性的鉴别器方法、容忍读取器的实现模式、在部署新格式时先读后写策略,以及性能比较。最后,涵盖了Akka.NET Actor系统的序列化配置和一系列最佳实践,确保开发者能够做出明智的选择,构建健壮、高性能且可维护的序列化层。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/serialization

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

.NET 中的序列化

何时使用本技能

在以下情况下使用本技能:

  • 为API、消息传递或持久化选择序列化格式
  • 从Newtonsoft.Json迁移到System.Text.Json
  • 实现AOT兼容的序列化
  • 设计分布式系统的线缆格式
  • 优化序列化性能

基于模式 vs 基于反射

方面基于模式基于反射
示例Protobuf、MessagePack、System.Text.Json (源代码生成)Newtonsoft.Json、BinaryFormatter
载荷中的类型信息否 (外部模式)是 (嵌入了类型名称)
版本控制明确的字段编号/名称隐式 (根据类型结构)
性能快 (无反射)较慢 (运行时反射)
AOT 兼容是否
线缆兼容性优秀差

建议:对于任何跨越进程边界的序列化,请使用基于模式的序列化。


格式推荐

使用场景推荐格式原因
REST APISystem.Text.Json (源代码生成)标准、AOT兼容
gRPCProtocol Buffers原生格式,出色的版本控制
Actor 消息传递MessagePack 或 Protobuf紧凑、快速、版本安全
事件溯源Protobuf 或 MessagePack必须永远处理旧事件
缓存MessagePack紧凑、快速
配置JSON (System.Text.Json)人类可读
日志记录JSON (System.Text.Json)结构化、可解析

应避免的格式

格式问题
BinaryFormatter安全漏洞、已弃用、永远不要使用
Newtonsoft.Json 默认载荷中的类型名称在重命名时会被破坏
DataContractSerializer复杂、版本控制差
XML冗长、慢、复杂

System.Text.Json 与源代码生成器

对于JSON序列化,使用带有源代码生成器的System.Text.Json,以获得AOT兼容性和性能。

设置

// 定义一个包含所有类型的 JsonSerializerContext
[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 { }

用法

// 使用上下文序列化
var json = JsonSerializer.Serialize(order, AppJsonContext.Default.Order);

// 使用上下文反序列化
var order = JsonSerializer.Deserialize(json, AppJsonContext.Default.Order);

// 在ASP.NET Core中配置
builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default);
});

优点

  • 运行时无反射 - 所有类型信息在编译时生成
  • AOT 兼容 - 可与 Native AOT 发布一起使用
  • 更快 - 无需运行时类型分析
  • 裁剪安全 - 链接器确切知道需要什么

Protocol Buffers (Protobuf)

最佳用途:Actor系统、gRPC、事件溯源、任何长期存在的线缆格式。

设置

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

定义模式

// orders.proto
syntax = "proto3";

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

    // 添加新字段总是安全的
    string notes = 5;  // 在v2中添加 - 旧读者会忽略它
}

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

版本控制规则

// 安全:使用新编号添加新字段
message Order {
    string id = 1;
    string customer_id = 2;
    string shipping_address = 5;  // 新增 - 安全
}

// 安全:删除字段(旧读者忽略未知字段,新读者使用默认值)
// 只需停止使用该字段,保留其编号
message Order {
    string id = 1;
    // customer_id 已删除,但字段 2 被保留
    reserved 2;
}

// 不安全:更改字段类型
message Order {
    int32 id = 1;  // 之前是:string - 破坏!
}

// 不安全:重复使用字段编号
message Order {
    reserved 2;
    string new_field = 2;  // 重复使用2 - 破坏!
}

MessagePack

最佳用途:高性能场景、紧凑的载荷、Actor消息传递。

设置

dotnet add package MessagePack
dotnet add package MessagePack.Annotations

使用契约

[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; }

    // 新字段 - 旧读者会跳过未知键
    [Key(4)]
    public string? Notes { get; init; }
}

// 序列化
var bytes = MessagePackSerializer.Serialize(order);

// 反序列化
var order = MessagePackSerializer.Deserialize<Order>(bytes);

AOT 兼容设置

// 使用源代码生成器以实现AOT
[MessagePackObject]
public partial class Order { }  // partial 启用源代码生成

// 配置解析器
var options = MessagePackSerializerOptions.Standard
    .WithResolver(CompositeResolver.Create(
        GeneratedResolver.Instance,  // 生成的
        StandardResolver.Instance));

从 Newtonsoft.Json 迁移

常见问题

NewtonsoftSystem.Text.Json修复
JSON中的 $type默认不支持使用鉴别器或自定义转换器
JsonPropertyJsonPropertyName不同的属性
DefaultValueHandlingDefaultIgnoreCondition不同的API
NullValueHandlingDefaultIgnoreCondition不同的API
私有setter需要 [JsonInclude]显式选择加入
多态性[JsonDerivedType] (.NET 7+)显式鉴别器

迁移模式

// Newtonsoft (基于反射)
public class Order
{
    [JsonProperty("order_id")]
    public string Id { get; set; }

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

// System.Text.Json (源代码生成兼容)
public sealed record Order(
    [property: JsonPropertyName("order_id")]
    string Id,

    string? Notes  // 通过 JsonSerializerOptions 处理 null
);

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

使用鉴别器的多态性

// .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);

// 序列化为:
// { "$type": "credit_card", "amount": 100, "last4": "1234" }

线缆兼容性模式

容忍读取器

旧代码必须安全地忽略未知字段:

// Protobuf/MessagePack:自动 - 跳过未知字段
// System.Text.Json:配置为允许
var options = new JsonSerializerOptions
{
    UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip
};

先读后写

在部署新格式的序列化器之前,先部署其反序列化器:

// 阶段1:添加反序列化器(部署到所有地方)
public Order Deserialize(byte[] data, string manifest) => manifest switch
{
    "Order.V1" => DeserializeV1(data),
    "Order.V2" => DeserializeV2(data),  // 新增 - 可以读取V2
    _ => throw new NotSupportedException()
};

// 阶段2:启用序列化器(下一个版本,在V1部署到所有地方之后)
public (byte[] data, string manifest) Serialize(Order order) =>
    _useV2Format
        ? (SerializeV2(order), "Order.V2")
        : (SerializeV1(order), "Order.V1");

永远不要嵌入类型名称

// 不好:载荷中的类型名称 - 重命名类会破坏线缆格式
{
    "$type": "MyApp.Order, MyApp.Core",
    "id": "123"
}

// 好:显式鉴别器 - 重构安全
{
    "type": "order",
    "id": "123"
}

性能比较

近似吞吐量(越高越好):

格式序列化反序列化大小
MessagePack★★★★★★★★★★★★★★★
Protobuf★★★★★★★★★★★★★★★
System.Text.Json (源代码生成)★★★★☆★★★★☆★★★☆☆
System.Text.Json (反射)★★★☆☆★★★☆☆★★★☆☆
Newtonsoft.Json★★☆☆☆★★☆☆☆★★★☆☆

对于热路径,首选 MessagePack 或 Protobuf。


Akka.NET 序列化

对于 Akka.NET Actor 系统,使用基于模式的序列化:

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

参见 Akka.NET 序列化文档。


最佳实践

要这样做

// 使用 System.Text.Json 的源代码生成器
[JsonSerializable(typeof(Order))]
public partial class AppJsonContext : JsonSerializerContext { }

// 使用显式字段编号/键
[MessagePackObject]
public class Order
{
    [Key(0)] public string Id { get; init; }
}

// 使用记录来表示不可变的消息类型
public sealed record OrderCreated(OrderId Id, CustomerId CustomerId);

不要这样做

// 不要使用 BinaryFormatter(永远)
var formatter = new BinaryFormatter();  // 安全风险!

// 不要在线缆格式中嵌入类型名称
settings.TypeNameHandling = TypeNameHandling.All;  // 重命名时破坏!

// 不要在热路径上使用反射序列化
JsonConvert.SerializeObject(order);  // 慢,不兼容 AOT

资源

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.

相关技能