杰克逊反序列化枚举值

时间:2017-10-09 17:27:23

标签: java spring enums jackson

当我传递空值时,我可以为枚举设置默认值吗?

public enum Something {
@JsonEnumDefaultValue
A(new BigDecimal(123)),
B(new BigDecimal(555)),
C(new BigDecimal(21312));

private BigDecimal value;

Something(BigDecimal value) {
    this.value = value;
}

public BigDecimal getValue() {
    return value;
}

}

我将这个枚举作为我的DTO中的字段,当我传递空值时 - jackon将其反序列化为null,但是当我传递一些奇怪的东西时 - 它设置了默认值。我的杰克逊配置在这里:

@Bean
public ObjectMapper mapper() {
    val mapper = new ObjectMapper();
    return mapper.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE);
}

Dto课程:

public class Dto {
private Something something;
private Smth smth;
private String name;
}

控制器:

@PostMapping
public ResponseEntity<Long> saveEntity(@RequestBody Dto dto) {
    return ResponseEntity.ok(repository.save(
            MyEntity.builder()
                    .name(dto.getName())
                    .something(dto.getSomething())
                    .smth(dto.getSmth())
                    .build())
            .getId());
}

1 个答案:

答案 0 :(得分:0)

您需要在类级别提供默认值,然后它将适用于空值。

E.g:

class Dto {
    private Something something = Something.A;
    private Smth smth;
    private String name;
}