title: Custom Serializers sidebar_position: 11 id: custom_serializers license: | Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Use a custom serializer when a type is not generated with [ForyStruct] or requires specialized encoding.
External-type serialization generates serializers for mutable third-party targets, including exact private or renamed fields. Use a custom serializer for immutable, constructor-only, factory-only, readonly, init-only, converted, or custom-wire targets. On .NET 8, a private external wire field whose declaring type or accessor signature is generic also requires a custom serializer. Exact storage-only mappings do not emit private accessors.
Serializer<T>using Apache.Fory; public sealed class Point { public int X { get; set; } public int Y { get; set; } } public sealed class PointSerializer : Serializer<Point> { public override Point DefaultValue => new(); public override void WriteData(WriteContext context, in Point value, bool hasGenerics) { context.Writer.WriteVarInt32(value.X); context.Writer.WriteVarInt32(value.Y); } public override Point ReadData(ReadContext context) { return new Point { X = context.Reader.ReadVarInt32(), Y = context.Reader.ReadVarInt32(), }; } }
Fory fory = Fory.Builder().Build(); fory.Register<Point, PointSerializer>(200); Point value = new() { X = 10, Y = 20 }; byte[] payload = fory.Serialize(value); Point decoded = fory.Deserialize<Point>(payload);
Use the named overload when peers identify the type by name instead of a numeric ID:
fory.Register<Point, PointSerializer>("com.example.Point");
WriteData / ReadData only handle payload content.Serializer<T>.Write / Read unless overridden.DefaultValue is used for null/default fallback paths.[ForyStruct] serializers for normal domain models.