user1472672
user1472672

Reputation: 365

Unable to use @Jacksonized with @JsonPOJOBuilder

I have the following simple POJO:

@Data
@Builder(builderClassName = "EmployeeBuilder")
@Jacksonized
public class Employee {

    private int identity;
    private String firstName;
    
    @JsonPOJOBuilder(buildMethodName = "createEmployee", withPrefix = "construct")
    public static class EmployeeBuilder {

        private int idValue;
        private String nameValue;

        public EmployeeBuilder constructId(int id) {
            idValue = id;
            return this;
        }
            
        public EmployeeBuilder constructName(String name) {
            nameValue = name;
            return this;
        }

        public Employee createEmployee() {
            return new Employee(idValue, nameValue);
        }
    }
}

Everything compiles and works in Eclipse OK, however when I try to compile via Maven and JDK jdk8u345-b01 I get the following error:

Employee.java:[15,8] com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder is not a repeatable annotation type

I've no idea what this even means to be honest but I'm using the latest version of Lombok 1.18.24 and Jackson 2.14.0

Thanks,

Upvotes: 0

Views: 733

Answers (1)

Jan Rieke
Jan Rieke

Reputation: 8042

Before explaining why this does not work, I must admit I do not understand what you are trying to achieve with your current code.

You are using a lombok @Builder, but you do a lot of customizing. Most confusing for me is that you define your own setter methods in the builder (with different names than the fields!) in addition to the setter methods generated by lombok. So you end up having a builder that has duplicate setter methods, and the way you implement it make the lombok-generated methods useless when calling createEmployee (their values will only be used in the lombok-generated build method, which in turn does not use the other values). This is heavily prone to wrong usage and bugs.

Just guessing: Are you doing this because fields in the JSON have different names than the fields you have in your POJO? If that's that case, your solution should be @JsonProperty("fieldNameInJson") on the fields in the POJO. In this way, you won't have to customize anything in the builder.

That being said, the problem here is that @Jacksonized generates all necessary annotations for you that make Jackson use the generated builder. However, you are interfering by adding one of those annotations (@JsonPOJOBuilder) yourself. Lombok adds a second @JsonPOJOBuilder, and that results in the error you are observing.

If you really need to add your own builder setter methods, reuse the builder fields of lombok when implementing a second setter method. Then use @Builder(buildMethodName = "createEmployee", setterPrefix = "construct") on the POJO class and remove the @JsonPOJOBuilder (lombok will create it for you).

Upvotes: 1

Related Questions