有没有办法使用Java 8 lambda样式添加自定义Jackson序列化程序? [英] Is there a way to use Java 8 lambda style to add custom Jackson serializer?

查看:223
本文介绍了有没有办法使用Java 8 lambda样式添加自定义Jackson序列化程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在通过Jackson模块添加Jackson自定义序列化程序是冗长的,并不适合新的Java 8 lambda模式。

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

有没有办法使用Java 8 lambda样式添加自定义Jackson序列化程序?

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

推荐答案

你可以制作一个简单的Jackson8Module,它可以让你做到以下几点:

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);

Jackson8Module代码只是扩展了Jackson SimpleModule以提供Java 8友好方法(可以扩展为支持其他方法)杰克逊模块方法):

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;
    }
}

以下是Jackson8Module的要点: https://gist.github.com/jeremychone/a7e06b8baffef88a8816

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

这篇关于有没有办法使用Java 8 lambda样式添加自定义Jackson序列化程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆