Lombok与来自camelCase的Jackson Deserializer

时间:2018-12-13 23:29:45

标签: java jackson lombok

这是一个简单的对象

@Builder
@Value
@JsonDeserialize(builder = User.UserBuilder.class)
class User {
    @NotNull
    @JsonProperty("user_name")
    private final string userName;

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

现在,如果我想使用ObjectMapper来读取一个字符串,我愿意

final User user = MAPPER.readValue("{\"user_name\":\"my-name\"}", User.class);

但这不会读取user_name,因为当我查看生成器生成的源代码时,会看到

public static final class UserBuilder {
    private String userName;
}

因此,camelCase与snake_case不匹配。通常,如果要手动生成Builder类,我也将@JsonProperty("user_name")放在builder属性上。

我该如何解决?

2 个答案:

答案 0 :(得分:1)

您可以配置ObjectMapper将驼峰式大小写转换为带下划线的名称:

objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

答案 1 :(得分:1)

Builder创建自己的构造函数,以与下划线参数名称一起使用:

@Value
@JsonDeserialize(builder = User.UserBuilder.class)
class User {
    @NotNull
    @JsonProperty("user_name")
    private final String userName;

    @Builder
    public User(String user_name) {
      this.userName = user_name;
    }

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

}