Quiero enviar un cuerpo de solicitud JSON donde los campos pueden ser valores de enumeración. Estos valores de enumeración están en camelCase, pero los valores de enumeración son UPPER_SNAKE_CASE.
Clases de 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; }Mi firma de punto final:
@PostMapping fun createPerson(@RequestBody person: CreatePersonDto)Solicitud HTTP:
curl -d '{ "firstName": "King", "lastName": "Leonidas", "idType": "drivingLicence" }' -H "Content-Type: application/json" -X POST http://localhost:8080/personQuiero convertir "permiso de conducir" a PERMISO DE CONDUCIR implícitamente.
org.springframework.core.convert.converter.Converter : funciona para @RequestParam , pero no para @RequestBodyorg.springframework.format.Formatter : registré este formateador, pero cuando realizo la solicitud, el método parse() no se ejecuta.Mi configuración hasta ahora:
@Configuration class WebConfig : WebMvcConfigurer { override fun addFormatters(registry: FormatterRegistry) { registry.addConverter(IdTypeConverter()) registry.addFormatter(IdTypeFormatter()) } }Puede intentar usar JsonProperty en enumeración directamente
enum IdType { @JsonProperty("drivingLicence") DRIVING_LICENCE, @JsonProperty("idCard") ID_CARD, @JsonProperty("passport") PASSPORT; } Si desea tener mapeo múltiple, lo simple sería definir el mapeo y usar JsonCreator en el nivel de enumeración:
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); } }Ver también: