You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

@RequestBody是否允许POJO未声明字段?如何配置返回Bad Request

解决Spring接口接收未知JSON字段不报错的问题

默认情况下,Spring Boot用Jackson处理JSON序列化/反序列化时,会自动忽略POJO里没定义的字段,所以你传额外参数时接口还是返回成功。要让这种情况返回Bad Request,有两种简单方法:

方法1:给POJO加注解

直接在你的NewsPOJO类上加上@JsonIgnoreProperties(ignoreUnknown = false),这样Jackson碰到未知字段就会抛出异常:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = false)
public class NewsPOJO {
    private String title;
    private String content;

    // 记得添加构造方法、getter和setter
}

方法2:全局配置Jackson(所有接口生效)

如果不想每个POJO都加注解,就在Spring Boot里加个配置类,全局开启严格校验:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.DeserializationFeature;

@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        // 开启未知字段报错
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
        return mapper;
    }
}

可选:自定义异常返回

开启上面的配置后,默认会返回500错误。如果要返回标准的400 Bad Request,加个全局异常处理器:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.fasterxml.jackson.databind.JsonMappingException;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(JsonMappingException.class)
    public ResponseEntity<String> handleUnknownFields(JsonMappingException e) {
        return new ResponseEntity<>("请求包含无效字段", HttpStatus.BAD_REQUEST);
    }
}

这样再用Postman传额外字段时,接口就会返回400响应了。

内容的提问来源于stack exchange,提问作者Sawant Aditya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 03:57:38