自定义序列化器
自定义序列化器允许你精确控制类型的序列化与反序列化过程。 This is useful for types that require special handling, optimization, or cross-language compatibility.
何时使用自定义序列化器
- Special encoding: Types that need a specific binary format
- Third-party types: Types from external libraries that Fory doesn't handle automatically
- Optimization: When you can serialize more efficiently than the default reflection-based approach
- Cross-language compatibility: When you need precise control over the binary format for interoperability
ExtensionSerializer 接口
Custom serializers implement the ExtensionSerializer interface:
type ExtensionSerializer interface {
// WriteData serializes the value to the buffer.
// Only write the data - Fory handles type info and references.
// Use ctx.Buffer() to access the ByteBuffer.
// Use ctx.SetError() to report errors.
WriteData(ctx *WriteContext, value reflect.Value)
// ReadData deserializes the value from the buffer into the provided value.
// Only read the data - Fory handles type info and references.
// Use ctx.Buffer() to access the ByteBuffer.
// Use ctx.SetError() to report errors.
ReadData(ctx *ReadContext, value reflect.Value)
}
基础示例
Here's a simple custom serializer for a type with an integer field:
import (
"reflect"
"github.com/apache/fory/go/fory"
)
type MyExt struct {
Id int32
}
type MyExtSerializer struct{}
func (s *MyExtSerializer) WriteData(ctx *fory.WriteContext, value reflect.Value) {
myExt := value.Interface().(MyExt)
ctx.Buffer().WriteVarint32(myExt.Id)
}
func (s *MyExtSerializer) ReadData(ctx *fory.ReadContext, value reflect.Value) {
id := ctx.Buffer().ReadVarint32(ctx.Err())
value.Set(reflect.ValueOf(MyExt{Id: id}))
}
// Register the custom serializer
f := fory.New()
err := f.RegisterExtension(MyExt{}, 100, &MyExtSerializer{})