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

Spring中@PostMapping接收对象列表时数值类型自动初始化问题求助

问题分析与解决方案

这不是Spring的bug,而是Jackson(Spring默认JSON解析器)的反序列化行为差异导致的:

  • Kotlin的Double/Int对应Java的基本数据类型,Jackson在反序列化集合内的对象时,若JSON缺失这类字段,会自动填充默认值(0/0.0);
  • 单个对象场景下,Jackson会严格校验构造函数参数的完整性,缺失字段直接抛出反序列化异常,返回Bad Request;
  • BigDecimal是引用类型,没有默认值,缺失时Jackson无法填充,直接抛出异常,因此能正常返回Bad Request。

解决方案1:全局配置Jackson强制校验缺失字段

通过修改Jackson的反序列化规则,让它在遇到data class的非空字段缺失时直接抛出异常,覆盖单个/集合对象的差异行为。

在Spring Boot的application.yml中添加配置:

spring:
  jackson:
    deserialization:
      fail-on-missing-creator-properties: true
      fail-on-null-creator-properties: true

或者用Kotlin配置类实现:

@Configuration
class JacksonConfig {
    @Bean
    fun jacksonCustomizer(): Jackson2ObjectMapperBuilderCustomizer {
        return Jackson2ObjectMapperBuilderCustomizer { builder ->
            builder.failOnMissingCreatorProperties(true)
                .failOnNullCreatorProperties(true)
        }
    }
}

配置生效后,只要JSON缺失非空字段,无论接收的是单个对象还是集合,Jackson都会抛出异常,Spring自动返回400 Bad Request。

解决方案2:结合JSR-380校验+可空字段

如果不想全局修改Jackson规则,可以通过可空字段配合校验注解实现需求:

  1. 引入Spring校验依赖(Spring Boot项目):
implementation 'org.springframework.boot:spring-boot-starter-validation'
  1. 修改Animal类,将字段改为可空类型并添加@NotNull注解:
data class Animal(
    val name: String,
    @field:NotNull(message = "height字段不能为空")
    val height: Double?
)
  1. 在Controller的列表参数上添加@Valid注解,触发集合内元素的校验:
@PostMapping("/animals")
@Validated
suspend fun saveAnimals(
    @RequestBody @Valid request: List<Animal>
): ResponseEntity<Any> {
    // 业务逻辑中可通过Kotlin的require确保height非空
    request.forEach { require(it.height != null) }
    println(request[0].height)
    return ResponseEntity.ok().build()
}

当JSON缺失height字段时,Jackson会将其设为null,@NotNull校验失败,Spring返回400 Bad Request。

内容的提问来源于stack exchange,提问作者Jordi Gomis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:35:33