suraj1291993
suraj1291993

Reputation: 473

Lombok builder pattern with jackson JsonProperty

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.

Upvotes: 20

Views: 27533

Answers (4)

Ant20
Ant20

Reputation: 2273

try update version

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
        <version>1.18.22</version>
    </dependency>

Upvotes: 1

Pawel Dobierski
Pawel Dobierski

Reputation: 457

As of Lombok v1.18.16, you should be able to use the @Jacksonized annotation.

@Data
@Jacksonized
@Builder
public class Pojo {

    @JsonProperty("package")
    String pkg;
}

Upvotes: 9

diginoise
diginoise

Reputation: 7620

Your mapper need to have a means of creating User class.

You could use constructor:

@NoArgsConstructor
@AllArgsConstructor
@Getter
@ToString
@Builder
class User {
  @JsonProperty("user_name")
  @NonNull
  private String userName;

  private int userId;
}

... or point it to builder as per Tomasz Linkowski's answer

Upvotes: 6

Tomasz Linkowski
Tomasz Linkowski

Reputation: 4496

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

Upvotes: 23

Related Questions