Community程式設計與開發github.com

序列化

為 .NET 應用程式選擇正確的序列化格式。優先使用基於 Schema 的格式(Protobuf、MessagePack),而非基於反射的格式(Newtonsoft.Json)。在 JSON 場景中使用搭配 AOT 原始碼產生器的 System.Text.Json。

序列化 是什麼?

此技能聚焦於協助 .NET 開發人員根據特定使用案例(如 REST API、gRPC、Actor 訊息傳遞或事件溯源)選擇並實作適當的序列化策略。它提倡基於 Schema 的格式(Protobuf、MessagePack、System.Text.Json 原始碼產生器),因為它們具有卓越的效能、AOT 相容性以及跨程序邊界的連線相容性,而非基於反射的方式(如 Newtonsoft.Json 或 BinaryFormatter)。文件提供了清晰的比較表格、依照使用案例的建議、詳細的程式碼範例,以及從舊式 .NET 序列化程式遷移的指導方針。它也討論了容忍讀者、先佈署反序列化器再佈署序列化器、以及永遠不要在酬載中嵌入型別名稱等模式,以確保長期維護的穩固性。

相容平台~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 相容的序列化
  • 設計分散式系統的連線格式
  • 最佳化序列化效能

基於 Schema 與基於反射的比較

面向基於 Schema基於反射
範例Protobuf、MessagePack、System.Text.Json (原始碼產生)Newtonsoft.Json、BinaryFormatter
酬載中的型別資訊無 (外部 Schema)有 (內嵌型別名稱)
版本管理明確的欄位編號/名稱隱含 (型別結構)
效能快速 (無反射)較慢 (執行階段反射)
AOT 相容是否
連線相容性極佳差

建議:對於任何跨越進程邊界的情況,請使用基於 Schema 的序列化。


格式建議

使用案例建議格式原因
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 { }

使用方式

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

// 使用 Context 反序列化
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

定義 Schema

// 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
私用設定器需要 [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 系統,請使用基於 Schema 的序列化:

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

// 對不可變的訊息型別使用 record
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.

相關技能