英文:
Deserialize requestParam enum case insensitive in spring boot using jackson
问题
我有以下API:
```java
@GetMapping(value = "/employees")
public List<Employee> getEmployees(
@RequestParam(value = "mode", required = false) final EmployeeMode mode) {
// 在这里调用服务
}
我有一个名为EmployeeMode的枚举作为请求参数。
public enum EmployeeMode {
REGULAR,
ALL,
TEMPORARY
}
我想要接受大小写不敏感的请求。尝试过@JsonAlias
、@JsonCreator
、objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, true)
以及spring.jackson.mapper.accept-case-insensitive-enums: true
,但都没有奏效。
我正在使用Spring Boot 2.5.5。
如何接受大小写不敏感的请求参数?如果请求参数为空/为null,想要将默认枚举设置为ALL。
<details>
<summary>英文:</summary>
I'm having below api
@GetMapping(value = "/employees")
public List<Employee> getEmployees(
@RequestParam(value = "mode", required = false) final EmployeeMode mode) {
//calling service from here
}
I'm having EmployeeMode enum as requestParam.
public enum EmployeeMode {
REGULAR,
ALL,
TEMPROARY
}
I want to accept request with case insensitive. Tried with ```@JsonAlias```, ```@JsonCreator``` and ```objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, true);``` and ```spring.jackson.mapper.accept-case-insensitive-enums: true```. nothing worked for me.
I'm using spring boot 2.5.5.
How to accept case insensitive request with requestParam? And if requestParam is empty/null, want to set default enum as ALL.
</details>
# 答案1
**得分**: 3
你可以通过实现转换器来处理它。
```java
public class EmployeeModeConverter implements Converter<String, EmployeeMode> {
@Override
public EmployeeMode convert(String source) {
switch (source.toUpperCase()) {
case "REGULAR": return EmployeeMode.Regular;
case "TEMPROARY": return EmployeeMode.TEMPROARY;
default: return EmployeeMode.ALL;
}
}
}
@Configuration
public class Config extends WebMvcConfigurationSupport {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new EmployeeModeConverter());
}
}
英文:
You can handle it by implementing converter.
public class EmployeeModeConverter implements Converter<String, EmployeeMode> {
@Override
public EmployeeMode convert(String source) {
switch (source.toUpperCase()) {
case "REGULAR": return EmployeeMode.Regular;
case "TEMPROARY": return EmployeeMode.TEMPROARY;
default: return EmployeeMode.ALL;
}
}
}
@Configuration
public class Config extends WebMvcConfigurationSupport {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new EmployeeModeConverter());
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论