Lombok builder pattern with jackson JsonProperty

suraj1291993 picture suraj1291993 · Aug 1, 2018 · Viewed 12.9k times · Source

I have constructed a Java Object using lombok with builder pattern. But, I am getting the following exception when trying to deserialize a Java object using Jackson. This occurs for fields which has @JsonProperty annotation.

Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "user_name" (class User$UserBuilder), not marked as ignorable (2 known properties: "userName", "userId"])
at [Source: (String)"{"userId":1,"user_name":"username"}"; line: 1, column: 26] (through reference chain: User$UserBuilder["user_name"])

Code Used :

public class TestJson {
    public static void main(String args[]) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();

        User user = User.builder()
                .userName("username")
                .userId(1)
                .build();
        System.out.println(user);
        String string = objectMapper.writeValueAsString(user);
        System.out.println(string);
        user = objectMapper.readValue(string, User.class);
        System.out.println(user);
    }
}


@JsonDeserialize(builder = User.UserBuilder.class)
@Getter
@ToString
@Builder(toBuilder = true)
class User {
    @JsonProperty("user_name")
    @NonNull
    private String userName;

    @JsonProperty
    private int userId;

    @JsonPOJOBuilder(withPrefix = "")
    public static class UserBuilder {

    }
}

Kindly help me solve this issue.

Thanks.

Answer

Tomasz Linkowski picture Tomasz Linkowski · Aug 1, 2018

You get this error because Jackson doesn't know how to map user_name to any of your UserBuilder fields.

You need @JsonProperty("user_name") on the userName field of UserBuilder too, like that:

@JsonPOJOBuilder(withPrefix = "")
public static class UserBuilder {

    @JsonProperty("user_name")
    @NonNull
    private String userName;
}