Spring Rest Controller中非数值参数的异常处理方案咨询
解决Spring接收非数值参数时字段赋值为null的问题
不需要将limit字段改为String类型,有几种优雅的方案可以实现解析失败时将字段设为null,同时避免返回400错误:
方案1:自定义Jackson反序列化器
针对Integer类型字段编写自定义反序列化逻辑,解析失败时返回null:
- 编写自定义反序列化类:
public class CustomIntegerDeserializer extends JsonDeserializer<Integer> { @Override public Integer deserialize(JsonParser parser, DeserializationContext context) throws IOException { String input = parser.getText(); try { return Integer.parseInt(input.trim()); } catch (NumberFormatException e) { // 解析失败返回null return null; } } }
- 在实体类字段上添加注解指定使用该反序列化器:
@Data public class API { @JsonDeserialize(using = CustomIntegerDeserializer.class) private Integer limit; }
方案2:通过@JsonSetter在Setter方法中处理
直接在实体类的Setter方法中接收字符串参数,手动处理转换逻辑:
@Data public class API { private Integer limit; @JsonSetter public void setLimit(String input) { try { this.limit = input == null ? null : Integer.parseInt(input.trim()); } catch (NumberFormatException e) { this.limit = null; } } }
方案3:全局配置Jackson(批量生效)
如果需要所有Integer类型字段都应用该逻辑,可以全局配置ObjectMapper,注册自定义反序列化器:
@Configuration public class JacksonGlobalConfig { @Bean public ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addDeserializer(Integer.class, new CustomIntegerDeserializer()); objectMapper.registerModule(module); return objectMapper; } }
以上方案都能实现:当请求传入无法转换为Integer的字符串时,limit字段会被赋值为null,接口正常返回200状态码,不会触发400错误。
内容的提问来源于stack exchange,提问作者Jmeter Tea
相关产品推荐
相关产品推荐

