# 使用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":"中国江西赣州",
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)