# 使用springboot @RequestBody接收不到指定字段的参数

使用springboot @RequestBody接收不到指定字段的参数

postman发送请求时,前端传的参数和后端规定的参数一样。但是通过@RequestBody接收参数时,始终为null。

后端实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Fruits {
    
      //水果
    private Integer fId;  //id
    private String name;  //名称
    private Double price;  //单价
    private Double vipPrice;  //会员单价
    private String describe;  //描述信息
    private String origin;  //产地
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
}

后端controller段代码

    @PutMapping
    public Result update(@RequestBody Fruits fruits) {
    
    
        log.info(fruits.toString());
        log.info("修改id为{}的水果",fruits.getFId());
//        fruitsService.update(fruits);
        return Result.success();
    }

postman请求体

{
    
    
	"fId":11,
    "name":"脐橙",
    "price":6,
    "vipPrice":5,
    "describe":"navelorange",
    "origin":"中国江西赣州",
}

请求处理的日志信息

在这里插入图片描述

可以看到,fId字段的内容为null

后来我将fId改为其他名字,发现有的可以正常接收(如printId,id),有的还是不行(pId,tId)。这应该是springboot的小问题。

浏览相关博客,发现有博主和我有同样的问题:当后端字段使用小驼峰命名时,确会有这样封装不到这样的问题。

解决方案

前端的请求体json格式数据的字段尽量使用小写字母命名,多个单词用下划线隔开。

此时后端对应的成员变量名若还想使用小驼峰命名,可在成员变量上加@jsonProperty(value="xxx")注解, xxx为请求参数的字段名,这样前端请求体json格式数据的xxx字段就能封装到对应的成员变量上了。

后端实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Fruits {
    
      //水果
    @JsonProperty(value = "f_id")
    private Integer fId;  //id
    private String name;  //名称
    private Double price;  //单价
    private Double vipPrice;  //会员单价
    private String describe;  //描述信息
    private String origin;  //产地
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
}

postman请求体

{
    
    
	"f_id":11,
    "name":"脐橙",
    "price":6,
    "vipPrice":5,
    "describe":"navelorange",
    "origin":"中国江西赣州",
}