【问题标题】:How to custom convert String to enum in @RequestBody?如何在@RequestBody 中自定义将字符串转换为枚举?
【发布时间】:2019-08-19 08:12:12
【问题描述】:

我想发送一个 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
)
enum class IdType {
    DRIVING_LICENCE,
    ID_CARD,
    PASSPORT;
}

我的端点签名:

@PostMapping
fun createPerson(@RequestBody person: CreatePersonDto)

HTTP 请求:

curl -d '{ "firstName": "King", "lastName": "Leonidas", "idType": "drivingLicence" }' -H "Content-Type: application/json" -X POST http://localhost:8080/person

我想将“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())
    }
}

【问题讨论】:

    标签: java spring-boot kotlin enums jackson


    【解决方案1】:

    你可以尝试直接在枚举上使用JsonProperty

    enum IdType {
    
        @JsonProperty("drivingLicence")
        DRIVING_LICENCE,
    
        @JsonProperty("idCard")
        ID_CARD,
    
        @JsonProperty("passport")
        PASSPORT;
    }
    

    如果您想进行多重映射,那么简单的事情就是定义映射并在枚举级别使用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);
        }
    }
    

    另见:

    【讨论】:

    • 如果我也想允许“drivingLicence”和“DRIVING_LICENCE”作为有效参数,解决方案是什么?
    猜你喜欢
    • 1970-01-01
    • 2016-07-30
    • 2010-10-03
    • 1970-01-01
    • 2022-01-10
    • 2013-06-27
    • 1970-01-01
    相关资源
    最近更新 更多