Is there a way to use the Java lambda style to add a custom Jackson serializer?

Adding a custom Jackson serializer through the Jackson module is currently verbose and not amenable to the new Java 8 lambda pattern.

Is there a way to use the Java 8 lambda style to add a custom Jackson serializer?

+6
source share
1 answer

You can create a simple Jackson8Module module that allows you to do the following:

ObjectMapper jacksonMapper = new ObjectMapper(); Jackson8Module module = new Jackson8Module(); module.addStringSerializer(LocalDate.class, (val) -> val.toString()); module.addStringSerializer(LocalDateTime.class, (val) -> val.toString()); jacksonMapper.registerModule(module); 

Jackson8Module code simply extends Jackson SimpleModule to provide Java 8 friendly methods (it can be extended to support other Jackson module methods):

 public class Jackson8Module extends SimpleModule { public <T> void addCustomSerializer(Class<T> cls, SerializeFunction<T> serializeFunction){ JsonSerializer<T> jsonSerializer = new JsonSerializer<T>() { @Override public void serialize(T t, JsonGenerator jgen, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { serializeFunction.serialize(t, jgen); } }; addSerializer(cls,jsonSerializer); } public <T> void addStringSerializer(Class<T> cls, Function<T,String> serializeFunction) { JsonSerializer<T> jsonSerializer = new JsonSerializer<T>() { @Override public void serialize(T t, JsonGenerator jgen, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { String val = serializeFunction.apply(t); jgen.writeString(val); } }; addSerializer(cls,jsonSerializer); } public static interface SerializeFunction<T> { public void serialize(T t, JsonGenerator jgen) throws IOException, JsonProcessingException; } } 

Here is the gist of Jackson8Module: https://gist.github.com/jeremychone/a7e06b8baffef88a8816

+4
source

Source: https://habr.com/ru/post/981569/


All Articles