Can't make Jackson and Lombok work together

后端 未结 14 1349
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 13:48

I am experimenting in combining Jackson and Lombok. Those are my classes:

package testelombok;

import com.fasterxml         


        
14条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 14:25

    If you want immutable but a json serializable POJO using lombok and jackson. Use jacksons new annotation on your lomboks builder @JsonPOJOBuilder(withPrefix = "") I tried this solution and it works very well. Sample usage

    import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
    import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
    import lombok.Builder;
    import lombok.Value;
    
    @JsonDeserialize(builder = Detail.DetailBuilder.class)
    @Value
    @Builder
    public class Detail {
    
        private String url;
        private String userName;
        private String password;
        private String scope;
    
        @JsonPOJOBuilder(withPrefix = "")
        public static class DetailBuilder {
    
        }
    }
    

    If you have too many classes with @Builder and you want don't want the boilerplate code empty annotation you can override the annotation interceptor to have empty withPrefix

    mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
            @Override
            public JsonPOJOBuilder.Value findPOJOBuilderConfig(AnnotatedClass ac) {
                if (ac.hasAnnotation(JsonPOJOBuilder.class)) {//If no annotation present use default as empty prefix
                    return super.findPOJOBuilderConfig(ac);
                }
                return new JsonPOJOBuilder.Value("build", "");
            }
        });
    

    And you can remove the empty builder class with @JsonPOJOBuilder annotation.

提交回复
热议问题