Skip to main content
Version: dev

Type Registration

Fory needs to know which class corresponds to which type in a serialized message. You do this by registering each class before you serialize or deserialize it.

Choosing a Registration Strategy

Fory offers two strategies. Pick one and use it consistently across every language that reads or writes the type.

Strategy 1: Numeric ID

Compact and fast. Good when a small team can coordinate IDs across services.

ModelsFory.register(fory, User, id: 100);

The same number must be used in every other language:

// Java side
fory.register(User.class, 100);

Strategy 2: Namespace + Type Name

More self-describing. Good when multiple teams or packages define types independently and numeric ID coordination is impractical.

ModelsFory.register(
fory,
User,
namespace: 'example',
typeName: 'User',
);

Every runtime that reads or writes this type must use the same namespace and typeName.

Do not mix strategies for the same type. If one side uses a numeric ID and the other uses a name, deserialization will fail.

Registering Generated Types

Call the generated register function from the .fory.dart file. It installs all the serializer metadata for you:

UserModelsFory.register(fory, User, id: 100);

Registering a Custom Serializer

For types that you cannot annotate with @ForyStruct(), pass a serializer instance directly:

fory.registerSerializer(
ExternalType,
const ExternalTypeSerializer(),
namespace: 'example',
typeName: 'ExternalType',
);

See Custom Serializers for how to implement a serializer.

Rules to Follow

  • Register before the first serialize or deserialize call.
  • Register every class that can appear in a message, not only the root type.
  • Keep IDs (or names) stable once payloads are persisted or exchanged across services. Changing them will break deserialization of old messages.
  • Do not mix a numeric ID on one side with a name on the other for the same type.

Cross-Language Requirements

The same numeric ID or namespace + typeName pair must be used in every runtime that reads or writes the type. See Cross-Language for examples.