I have this dto.
@Data
public class ProductDto implements Serializable {
private Long id;
private String name;
private String title;
private String price;
private String quantity;
}
I would like to write custom serializer, adding or removing some fields from sending. for example "title". Now i have this.
public class ProductKafkaSerializer implements Serializer<ProductDto> {
private final Boolean isTitleEnabled;
public ProductKafkaSerializer(@Value("${dto.product.fields.title.enabled}") Boolean isTitleEnabled) {
this.isTitleEnabled = isTitleEnabled;
}
private final ObjectMapper objectMapper = new ObjectMapper();
@Override
public byte[] serialize(String s, ProductDto productDto) {
try {
return objectMapper.writeValueAsBytes(productDto);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
it is possible?
I would like to do it the way im doing it using json serialization like this.
@JsonComponent
public class ProductSerializer extends JsonSerializer<ProductDto> {
private final Boolean isTitleEnabled;
public ProductSerializer(@Value("${dto.product.fields.title.enabled}") Boolean isTitleEnabled) {
this.isTitleEnabled = isTitleEnabled;
}
@Override
public void serialize(ProductDto productDto, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("id", String.valueOf(productDto.getId()));
jsonGenerator.writeStringField("name", productDto.getName());
if (isTitleEnabled)
jsonGenerator.writeStringField("title", productDto.getTitle());
jsonGenerator.writeStringField("quantity", productDto.getQuantity());
jsonGenerator.writeStringField("price", productDto.getPrice());
jsonGenerator.writeEndObject();
}
}