How to register a custom list serializer with Spring Boot / Jackson

public class LanguageString {

Locale locale;
String value;
}
{
"de": "hallo",
"en": "hello",
"fr": "bonjour"
}
  • Annotate every field that you want to use that serializer with @JsonSerializer(use = YourCustomSerializerClass.class). This is not a choice for us as we simply have the List<LanguageString> everywhere and we want to set a default behaviour for it.
  • Register your custom serializer with Jackson config and the data type. This normally works fine without collection type. After quite a bit of struggling to make it work and still failed, I came across the comment in Jackson’s SimpleModule.java:
/**
* Method for adding serializer to handle values of specific type.
*<p>
* WARNING! Type matching only uses type-erased {
@code Class} and should NOT
* be used when registering serializers for generic types like
* {
@link java.util.Collection} and {@link java.util.Map}.
*/
public class CollectionTypeJsonSerializer extends SimpleSerializers {

@Override
public JsonSerializer<?> findCollectionSerializer(SerializationConfig config,
CollectionType type,
BeanDescription beanDesc,
TypeSerializer elementTypeSerializer,
JsonSerializer<Object> elementValueSerializer) {
//if the collection is of type LanguageString, then use custom collection serializer
if (isLanguageStringListType(type)) {
return new LanguageStringListSerializer();
}

return findSerializer(config, type, beanDesc);
}


private boolean isLanguageStringListType(CollectionType type) {
CollectionType languageStringArrayListType = TypeFactory.defaultInstance()
.constructCollectionType(ArrayList.class, LanguageString.class);

CollectionType languageStringListType = TypeFactory.defaultInstance()
.constructCollectionType(List.class, LanguageString.class);

return (type.equals(languageStringListType) || type.equals(languageStringArrayListType));
}
}
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper jsonObjectMapper() {
ArrayList<Module> modules = new ArrayList<>();

//CollectionType Serialization
SimpleModule collectionTypeSerializerModule = new SimpleModule();
collectionTypeSerializerModule.setSerializers(new CollectionTypeJsonSerializer());
modules.add(collectionTypeSerializerModule);

return Jackson2ObjectMapperBuilder.json()
.modules(modules)
.build();
}
}

--

--

Product engineer / novice writer (alexthered.me)

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store