如何在@RequestBody 中自定义将字符串转换为枚举?

Lor*_*ius 7 java enums jackson kotlin spring-boot

我想发送一个 JSON 请求正文,其中字段可以是枚举值。这些枚举值以驼峰命名,但枚举值为 UPPER_SNAKE_CASE。

Kotlin 类:

data class CreatePersonDto @JsonCreator constructor (
        @JsonProperty("firstName") val firstName: String,
        @JsonProperty("lastName") val lastName: String,
        @JsonProperty("idType") val idType: IdType
)
Run Code Online (Sandbox Code Playgroud)
enum class IdType {
    DRIVING_LICENCE,
    ID_CARD,
    PASSPORT;
}
Run Code Online (Sandbox Code Playgroud)

我的端点签名:

@PostMapping
fun createPerson(@RequestBody person: CreatePersonDto)
Run Code Online (Sandbox Code Playgroud)

HTTP请求:

curl -d '{ "firstName": "King", "lastName": "Leonidas", "idType": "drivingLicence" }' -H "Content-Type: application/json" -X POST http://localhost:8080/person
Run Code Online (Sandbox Code Playgroud)

我想隐式地将“drivingLicence”转换为 DRIVING_LICENCE。

我试过了:

  • org.springframework.core.convert.converter.Converter: 它适用于@RequestParam,但不适用于@RequestBody
  • org.springframework.format.Formatter: 我注册了这个格式化程序,但是当我发出请求时,parse()方法没有执行。

到目前为止我的配置:

@Configuration
class WebConfig : WebMvcConfigurer {

    override fun addFormatters(registry: FormatterRegistry) {
        registry.addConverter(IdTypeConverter())
        registry.addFormatter(IdTypeFormatter())
    }
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ber 7

您可以尝试JsonProperty直接在 enum上使用

enum IdType {

    @JsonProperty("drivingLicence")
    DRIVING_LICENCE,

    @JsonProperty("idCard")
    ID_CARD,

    @JsonProperty("passport")
    PASSPORT;
}
Run Code Online (Sandbox Code Playgroud)

如果您想进行多重映射,那么简单的事情就是JsonCreator在枚举级别定义映射和使用:

enum IdType {

    DRIVING_LICENCE,
    ID_CARD,
    PASSPORT;

    private static Map<String, IdType> mapping = new HashMap<>();

    static {
        mapping.put("drivingLicence", DRIVING_LICENCE);
        mapping.put(DRIVING_LICENCE.name(), DRIVING_LICENCE);
        // ...
    }

    @JsonCreator
    public static IdType fromString(String value) {
        return mapping.get(value);
    }
}
Run Code Online (Sandbox Code Playgroud)

也可以看看: