Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jackson

Right now adding Jackson custom serializer via Jackson module is verbose and does not lend itself to the new Java 8 lambda pattern.

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

like image 499
Jeremy Chone Avatar asked Jan 26 '15 18:01

Jeremy Chone


People also ask

Can we replace lambda expression with method reference?

The method references can only be used to replace a single method of the lambda expression.

How do I make lambda serializable?

We can serialize a lambda expression if its target type and its captured arguments have serialized. However, like inner classes, the serialization of lambda expressions is strongly discouraged. As the lambda function is not serialized by default we simply have to cast our lambda to java. io.

Does Jackson use Java serialization?

This short tutorial shows how the Jackson library can be used to serialize Java object to XML and deserialize them back to objects.


1 Answers

You can make a simple Jackson8Module that would allow 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);

The Jackson8Module code just 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 the Jackson8Module: https://gist.github.com/jeremychone/a7e06b8baffef88a8816

like image 104
Jeremy Chone Avatar answered Sep 28 '22 12:09

Jeremy Chone