Can't make Jackson and Lombok work together
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@Builderpublic 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.
Immutable + Lombok + Jackson can be achieved in next way:
import com.fasterxml.jackson.databind.ObjectMapper;import lombok.AccessLevel;import lombok.AllArgsConstructor;import lombok.NoArgsConstructor;import lombok.Value;@Value@NoArgsConstructor(force = true, access = AccessLevel.PRIVATE)@AllArgsConstructorpublic class LocationDto { double longitude; double latitude;}class ImmutableWithLombok { public static void main(String[] args) throws Exception { ObjectMapper objectMapper = new ObjectMapper(); String stringJsonRepresentation = objectMapper.writeValueAsString(new LocationDto(22.11, 33.33)); System.out.println(stringJsonRepresentation); LocationDto locationDto = objectMapper.readValue(stringJsonRepresentation, LocationDto.class); System.out.println(locationDto); }}
I tried several of the above and they were all temperamental.What really worked for me is the the answer I found here.
on your project's root directory add a lombok.config file (if you haven't done already)
lombok.config
and inside paste this
lombok.anyConstructor.addConstructorProperties=true
Then you can define your pojos like the following:
@Data@AllArgsConstructorpublic class MyPojo { @JsonProperty("Description") private String description; @JsonProperty("ErrorCode") private String errorCode;}