serialization by aaronontheweb/dotnet-skills
npx skills add https://github.com/aaronontheweb/dotnet-skills --skill serialization在以下情况时使用此技能:
| 方面 | 基于模式 | 基于反射 |
|---|---|---|
| 示例 | Protobuf、MessagePack、System.Text.Json(源生成) | Newtonsoft.Json、BinaryFormatter |
| 有效载荷中的类型信息 | 无(外部模式) | 有(嵌入类型名称) |
| 版本控制 | 显式字段编号/名称 | 隐式(类型结构) |
| 性能 | 快(无反射) | 较慢(运行时反射) |
| AOT 兼容 | 是 | 否 |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
| 有线兼容性 | 优秀 | 差 |
建议:对于任何跨越进程边界的情况,使用基于模式的序列化。
| 使用场景 | 推荐格式 | 原因 |
|---|---|---|
| REST API | System.Text.Json(源生成) | 标准、AOT 兼容 |
| gRPC | Protocol Buffers | 原生格式,版本控制优秀 |
| Actor 消息传递 | MessagePack 或 Protobuf | 紧凑、快速、版本安全 |
| 事件溯源 | Protobuf 或 MessagePack | 必须永久处理旧事件 |
| 缓存 | MessagePack | 紧凑、快速 |
| 配置 | JSON(System.Text.Json) | 人类可读 |
| 日志记录 | JSON(System.Text.Json) | 结构化、可解析 |
| 格式 | 问题 |
|---|---|
| BinaryFormatter | 安全漏洞、已弃用、切勿使用 |
| Newtonsoft.Json 默认 | 有效载荷中的类型名称在重命名时会破坏 |
| DataContractSerializer | 复杂、版本控制差 |
| XML | 冗长、缓慢、复杂 |
对于 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);
});
最适合: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 - 破坏性更改!
}
最适合:高性能场景、紧凑有效载荷、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 使用源生成器
[MessagePackObject]
public partial class Order { } // partial 启用源生成
// 配置解析器
var options = MessagePackSerializerOptions.Standard
.WithResolver(CompositeResolver.Create(
GeneratedResolver.Instance, // 生成的
StandardResolver.Instance));
| Newtonsoft | System.Text.Json | 修复方法 |
|---|---|---|
JSON 中的 $type | 默认不支持 | 使用鉴别器或自定义转换器 |
JsonProperty | JsonPropertyName | 不同的属性 |
DefaultValueHandling | DefaultIgnoreCondition | 不同的 API |
NullValueHandling | DefaultIgnoreCondition | 不同的 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 处理空值
);
[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 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
每周安装次数
97
代码仓库
GitHub 星标数
491
首次出现
2026 年 1 月 28 日
安全审计
安装在
claude-code73
codex64
opencode63
github-copilot62
gemini-cli60
kimi-cli57
Use this skill when:
| Aspect | Schema-Based | Reflection-Based |
|---|---|---|
| Examples | Protobuf, MessagePack, System.Text.Json (source gen) | Newtonsoft.Json, BinaryFormatter |
| Type info in payload | No (external schema) | Yes (type names embedded) |
| Versioning | Explicit field numbers/names | Implicit (type structure) |
| Performance | Fast (no reflection) | Slower (runtime reflection) |
| AOT compatible | Yes | No |
| Wire compatibility | Excellent | Poor |
Recommendation : Use schema-based serialization for anything that crosses process boundaries.
| Use Case | Recommended Format | Why |
|---|---|---|
| REST APIs | System.Text.Json (source gen) | Standard, AOT-compatible |
| gRPC | Protocol Buffers | Native format, excellent versioning |
| Actor messaging | MessagePack or Protobuf | Compact, fast, version-safe |
| Event sourcing | Protobuf or MessagePack | Must handle old events forever |
| Caching | MessagePack | Compact, fast |
| Configuration | JSON (System.Text.Json) | Human-readable |
| Logging | JSON (System.Text.Json) | Structured, parseable |
| Format | Problem |
|---|---|
| BinaryFormatter | Security vulnerabilities, deprecated, never use |
| Newtonsoft.Json default | Type names in payload break on rename |
| DataContractSerializer | Complex, poor versioning |
| XML | Verbose, slow, complex |
For JSON serialization, use System.Text.Json with source generators for AOT compatibility and performance.
// Define a JsonSerializerContext with all your types
[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 { }
// Serialize with context
var json = JsonSerializer.Serialize(order, AppJsonContext.Default.Order);
// Deserialize with context
var order = JsonSerializer.Deserialize(json, AppJsonContext.Default.Order);
// Configure in ASP.NET Core
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default);
});
Best for: Actor systems, gRPC, event sourcing, any long-lived wire format.
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;
// Adding new fields is always safe
string notes = 5; // Added in v2 - old readers ignore it
}
message OrderItem {
string product_id = 1;
int32 quantity = 2;
int64 price_cents = 3;
}
// SAFE: Add new fields with new numbers
message Order {
string id = 1;
string customer_id = 2;
string shipping_address = 5; // NEW - safe
}
// SAFE: Remove fields (old readers ignore unknown, new readers use default)
// Just stop using the field, keep the number reserved
message Order {
string id = 1;
// customer_id removed, but field 2 is reserved
reserved 2;
}
// UNSAFE: Change field types
message Order {
int32 id = 1; // Was: string - BREAKS!
}
// UNSAFE: Reuse field numbers
message Order {
reserved 2;
string new_field = 2; // Reusing 2 - BREAKS!
}
Best for: High-performance scenarios, compact payloads, actor messaging.
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; }
// New field - old readers skip unknown keys
[Key(4)]
public string? Notes { get; init; }
}
// Serialize
var bytes = MessagePackSerializer.Serialize(order);
// Deserialize
var order = MessagePackSerializer.Deserialize<Order>(bytes);
// Use source generator for AOT
[MessagePackObject]
public partial class Order { } // partial enables source gen
// Configure resolver
var options = MessagePackSerializerOptions.Standard
.WithResolver(CompositeResolver.Create(
GeneratedResolver.Instance, // Generated
StandardResolver.Instance));
| Newtonsoft | System.Text.Json | Fix |
|---|---|---|
$type in JSON | Not supported by default | Use discriminators or custom converters |
JsonProperty | JsonPropertyName | Different attribute |
DefaultValueHandling | DefaultIgnoreCondition | Different API |
NullValueHandling |
// Newtonsoft (reflection-based)
public class Order
{
[JsonProperty("order_id")]
public string Id { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string? Notes { get; set; }
}
// System.Text.Json (source-gen compatible)
public sealed record Order(
[property: JsonPropertyName("order_id")]
string Id,
string? Notes // Null handling via JsonSerializerOptions
);
[JsonSerializable(typeof(Order))]
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.SnakeCaseLower,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
public partial class OrderJsonContext : JsonSerializerContext { }
// .NET 7+ polymorphism
[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);
// Serializes as:
// { "$type": "credit_card", "amount": 100, "last4": "1234" }
Old code must safely ignore unknown fields:
// Protobuf/MessagePack: Automatic - unknown fields skipped
// System.Text.Json: Configure to allow
var options = new JsonSerializerOptions
{
UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip
};
Deploy deserializers before serializers for new formats:
// Phase 1: Add deserializer (deployed everywhere)
public Order Deserialize(byte[] data, string manifest) => manifest switch
{
"Order.V1" => DeserializeV1(data),
"Order.V2" => DeserializeV2(data), // NEW - can read V2
_ => throw new NotSupportedException()
};
// Phase 2: Enable serializer (next release, after V1 deployed everywhere)
public (byte[] data, string manifest) Serialize(Order order) =>
_useV2Format
? (SerializeV2(order), "Order.V2")
: (SerializeV1(order), "Order.V1");
// BAD: Type name in payload - renaming class breaks wire format
{
"$type": "MyApp.Order, MyApp.Core",
"id": "123"
}
// GOOD: Explicit discriminator - refactoring safe
{
"type": "order",
"id": "123"
}
Approximate throughput (higher is better):
| Format | Serialize | Deserialize | Size |
|---|---|---|---|
| MessagePack | ★★★★★ | ★★★★★ | ★★★★★ |
| Protobuf | ★★★★★ | ★★★★★ | ★★★★★ |
| System.Text.Json (source gen) | ★★★★☆ | ★★★★☆ | ★★★☆☆ |
| System.Text.Json (reflection) | ★★★☆☆ | ★★★☆☆ | ★★★☆☆ |
| Newtonsoft.Json | ★★☆☆☆ | ★★☆☆☆ | ★★★☆☆ |
For hot paths, prefer MessagePack or Protobuf.
For Akka.NET actor systems, use schema-based serialization:
akka {
actor {
serializers {
messagepack = "Akka.Serialization.MessagePackSerializer, Akka.Serialization.MessagePack"
}
serialization-bindings {
"MyApp.Messages.IMessage, MyApp" = messagepack
}
}
}
See Akka.NET Serialization Docs.
// Use source generators for System.Text.Json
[JsonSerializable(typeof(Order))]
public partial class AppJsonContext : JsonSerializerContext { }
// Use explicit field numbers/keys
[MessagePackObject]
public class Order
{
[Key(0)] public string Id { get; init; }
}
// Use records for immutable message types
public sealed record OrderCreated(OrderId Id, CustomerId CustomerId);
// Don't use BinaryFormatter (ever)
var formatter = new BinaryFormatter(); // Security risk!
// Don't embed type names in wire format
settings.TypeNameHandling = TypeNameHandling.All; // Breaks on rename!
// Don't use reflection serialization for hot paths
JsonConvert.SerializeObject(order); // Slow, not AOT-compatible
Weekly Installs
97
Repository
GitHub Stars
491
First Seen
Jan 28, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
claude-code73
codex64
opencode63
github-copilot62
gemini-cli60
kimi-cli57
Swift Actor 线程安全持久化:构建离线优先应用的编译器强制安全数据层
1,700 周安装
Elastic Observability SLO管理指南:创建、监控服务等级目标与SLI类型详解
204 周安装
CSS开发指南:Flexbox、Grid布局、响应式设计与性能优化最佳实践
199 周安装
OpenSpec (OPSX) 指南:基于工件的开发工作流系统,实现变更管理与自动化
202 周安装
React Testing Library 测试最佳实践:用户行为测试、查询优先级与异步处理指南
200 周安装
Web无障碍测试指南:WCAG合规、键盘导航与屏幕阅读器测试最佳实践
202 周安装
化学分析师技能:原子理论、热力学、光谱学、色谱法、合成路线规划与材料表征
200 周安装
DefaultIgnoreCondition| Different API |
| Private setters | Requires [JsonInclude] | Explicit opt-in |
| Polymorphism | [JsonDerivedType] (.NET 7+) | Explicit discriminators |