I have a POJO to be serialized which has field of type Object
named representation
and I have a custom serializer written for it.
Just to add to the excellent answer by cassiomolin if you're trying to use this with Spring Boot and Kotlin to use your custom Jackson ObjectMapper:
// the custom serializer
class CustomSerializer : JsonSerializer<Any>() {
override fun serialize(value: Any?,
gen: JsonGenerator?,
serializers: SerializerProvider?) {
gen?.let {
gen.writeObject(content)
// ...
}
}
}
// the mixin
interface EventMixIn {
@JsonProperty("representation")
@JsonSerialize(using = CustomSerializer::class)
fun getRepresentation(): Any?
}
// the config with the bean
@Configuration
class AppConfig {
@Bean
fun createObjectMapper(): MappingJackson2HttpMessageConverter {
val objectMapper = ObjectMapper()
objectMapper.addMixIn(Event::class.java, EventMixIn::class.java)
return MappingJackson2HttpMessageConverter(objectMapper)
}
}
Have you ever considered Jackson mix-in annotations?
It's a great alternative when modifying the classes is not an option. You can think of it as kind of aspect-oriented way of adding more annotations during runtime, to augment statically defined ones.
Define a mix-in annotation interface (class would do as well):
public interface EventMixIn {
@JsonProperty("representation")
@JsonSerialize(using = CustomSerializer.class)
Object getRepresentation();
}
Then configure ObjectMapper
to use the defined interface as a mix-in for your POJO:
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
.addMixIn(User.Event.class, EventMixIn.class);
Here are some usage considerations:
private
, protected
, ...) and method implementations are ignored.For more details, you can have a look at this page.