请求接口
接口如下:
@GetMapping()
@ApiOperation("查询 App 列表")
public List<AppVO> queryApps(
@RequestParam(required = false) Long id,
@RequestParam(required = false) String name,
@RequestParam(required = false) AppSpace space,
@RequestParam(required = false) Integer platform,
@RequestParam(required = false) Integer productId) {
}
其中 AppSpace 是个枚举,定义如下(只列出和json序列化相关的代码):
@JsonCreator
public static AppSpace findByString(String name) {
for (AppSpace item : AppSpace.values()) {
if (item.name.equals(name)) {
return item;
}
}
return null;
}
@JsonValue
public String toString() {
return this.name;
}
报错信息
{
"message": "Failed to convert value of type 'java.lang.String'
to required type 'AppSpace';
nested exception is org.springframework.core.convert.ConversionFailedException:
Failed to convert from type [java.lang.String] to type
[@org.springframework.web.bind.annotation.RequestParam AppSpace] for value 'space'; nested
exception is java.lang.ClassCastException: AppSpace cannot be cast to
java.util.Optional"
}
解决办法
让 AppSpace 用 @JsonCreator 注解的反序列方法,返回 Optional,如下:
@JsonCreator
public static Optional<AppSpace> findByString(String name) {
for (AppSpace item : AppSpace.values()) {
if (item.name.equals(name)) {
return Optional.of(item);
}
}
return Optional.empty();
}