LordSerius:
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.
Kotlin clases:
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 criterio de valoración:
@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/person
Quiero convertir "permisoConducir" a DRIVING_LICENCE implícita.
Yo he tratado:
org.springframework.core.convert.converter.Converter
: Funciona para@RequestParam
, pero no para@RequestBody
org.springframework.format.Formatter
: Me he registrado este formateador, pero cuando hago la solicitud de laparse()
que no se ejecute el método.
Mi configuración hasta el momento:
@Configuration
class WebConfig : WebMvcConfigurer {
override fun addFormatters(registry: FormatterRegistry) {
registry.addConverter(IdTypeConverter())
registry.addFormatter(IdTypeFormatter())
}
}
Michael Ziober:
Usted puede tratar de utilizar JsonProperty
en la enumeración directamente
enum IdType {
@JsonProperty("drivingLicence")
DRIVING_LICENCE,
@JsonProperty("idCard")
ID_CARD,
@JsonProperty("passport")
PASSPORT;
}
Si usted quiere tener multimapping lo sencillo sería definir la cartografía y el uso 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: