In some cases, we might need to serialize/deserialize a pojo or a bean using a custom serializer instead of the default ones, Domino-jackson allows registering custom serializers/deserializers in two different ways :
In this case, we use a special annotations to define a custom serializers/deserializers CustomSerializer and CustomDeserializer The processor will pick those up before starting generating mapper for the classes. For example :
Custom Serializer :
package org.dominokit.jackson.processor.custom;
import static java.util.Objects.nonNull;
import org.dominokit.jackson.JsonSerializationContext;
import org.dominokit.jackson.JsonSerializer;
import org.dominokit.jackson.JsonSerializerParameters;
import org.dominokit.jackson.annotation.CustomSerializer;
import org.dominokit.jackson.stream.JsonWriter;
@CustomSerializer(Employee.class)
public class CustomBeanSerializer extends JsonSerializer<Employee> {
@Override
protected void doSerialize(JsonWriter writer, Employee value, JsonSerializationContext ctx,
JsonSerializerParameters params) {
if(nonNull(value)) {
writer.value(value.getId() + "," + value.getName() + "," + value.getTitle());
}else {
writer.value("");
}
}
}
Custom Deserializer :
package org.dominokit.jackson.processor.custom;
import static java.util.Objects.nonNull;
import org.dominokit.jackson.JsonDeserializationContext;
import org.dominokit.jackson.JsonDeserializer;
import org.dominokit.jackson.JsonDeserializerParameters;
import org.dominokit.jackson.annotation.CustomDeserializer;
import org.dominokit.jackson.stream.JsonReader;
@CustomDeserializer(Employee.class)
public class CustomBeanDeserializer extends JsonDeserializer<Employee> {
@Override
protected Employee doDeserialize(JsonReader reader, JsonDeserializationContext ctx,
JsonDeserializerParameters params) {
String value = reader.nextString();
if(nonNull(value)){
String[] split = value.split(",");
Employee bean = new Employee();
bean.setId(Long.parseLong(split[0]));
bean.setName(split[1]);
bean.setTitle(split[2]);
return bean;
}
return null;
}
}
In this case, we load the custom serializers/deserializers using service loaders, the processor will look for any service that implements CustomMappersLoader interface and load all registered mappers before generating mapper for the classes. For example :
External mappers loader :
package org.dominokit.jackson.test;
import com.google.auto.service.AutoService;
import org.dominokit.jackson.CustomMappersLoader;
import org.dominokit.jackson.RegistryWrapper;
@AutoService(CustomMappersLoader.class)
public class PersonCustomMappersLoader implements CustomMappersLoader {
@Override
public void register(RegistryWrapper registry) {
registry.registerSerializer(Person.class.getCanonicalName(), PersonCustomBeanSerializer.class);
registry.registerDeserializer(Person.class.getCanonicalName(), PersonCustomBeanDeserializer.class);
}
}