• 记一次springboot的@RequestBody json值注入失败的问题(字段大小写的问题)


    有时候做后端开发时,难免会与算法联调接口,很多算法的变量命名时全部大写,在实际springmvc开发中会遇到无法赋值的问题。

    先粘贴问题代码

    entity类

    1. @Data
    2. @NoArgsConstructor
    3. @EqualsAndHashCode(callSuper = true)
    4. @ToString(callSuper = true)
    5. public class EyeRequest extends CommonRequest {
    6. private Integer PRECLOSE;
    7. private Integer MDEC;
    8. private Integer BF;
    9. private Integer MAR;
    10. public EyeRequest(Integer timestamp, Integer PRECLOSE, Integer MDEC, Integer BF, Integer MAR) {
    11. super(ResponseConstant.EYE_TYPE, timestamp);
    12. this.PRECLOSE = PRECLOSE;
    13. this.MDEC = MDEC;
    14. this.BF = BF;
    15. this.MAR = MAR;
    16. }
    17. }

    controller类

    1. @PostMapping("/uploadMouseEyeMove")
    2. public CommonResponse uploadMouseEyeMove(@RequestBody EyeRequest eyeRequest) {
    3. log.info("eyeRequest:{}",eyeRequest);
    4. return callBackService.uploadMouseEyeMove(eyeRequest);
    5. }

    请求的body

    1. {
    2. "PRECLOSE": 1,
    3. "MDEC": 1,
    4. "BF": 1,
    5. "MAR": 1,
    6. "timestamp": 1111
    7. }

    在使用中发现字段没有被赋值

    eyeRequest:EyeRequest(super=CommonRequest(type=null, timestamp=1111), PRECLOSE=null, MDEC=null, BF=null, MAR=null)

    反复比对json的字段和java的字段,发现没有错误,debug源码,将断点打在log的那一行,首先,springmvc的请求数据统一由HttpMessageConverter这个接口处理,查看这个类的结构

    不难推测出,应该是使用read的方法进行赋值

    注释也证明了这一点,查看该类的实现类不难发现

    springboot是默认采用Jackson实现的,点击进入,查看read的方法

    第一个方法可以忽略,看方法名应该是获取Java的类的全路径,进入下面的方法后

    进入ObjectMapper类中

    debug到这里

    tips:可以通过在抽象方法打断点,ide会自动进入实现

    195行步入

    377行步入

    进入方法后发现所有的字段均为小写,我是用@Data,反编译源码后发现并不相符

    排查问题后发现springmvc在解析json时默认使用的解析工具时Jackson框架,Jackson会使用java约定的变量命名法,所以当全是大写字母的字段的时候在生成值得时候会出异常。

    解决方案:

    使用@JsonProperty注解重命名,上面的entity

    1. @Data
    2. @NoArgsConstructor
    3. @EqualsAndHashCode(callSuper = true)
    4. @ToString(callSuper = true)
    5. public class EyeRequest extends CommonRequest {
    6. @JsonProperty(value = "PRECLOSE")
    7. private Integer preclose;
    8. @JsonProperty(value = "MDEC")
    9. private Integer mdec;
    10. @JsonProperty(value = "BF")
    11. private Integer bf;
    12. @JsonProperty(value = "MAR")
    13. private Integer mar;
    14. public EyeRequest(Integer timestamp, Integer preclose, Integer mdec, Integer bf, Integer mar) {
    15. super(ResponseConstant.EYE_TYPE, timestamp);
    16. this.preclose = preclose;
    17. this.mdec = mdec;
    18. this.bf = bf;
    19. this.mar = mar;
    20. }
    21. }

    重新启动后可以成功赋值

  • 相关阅读:
    【精华系列】跟着Token学习数据挖掘-1
    11. Java的IO流
    服务端技术方案应该具有哪些章节
    技术20期:3种在 Python 中使用 Keras 库评估深度学习模型性能
    百家饭OpenAPI平台秋季更新-向全能OpenAPI编辑器挺进
    JavaScript深拷贝
    matlab数学建模方法与实践 笔记汇总
    flutter 开发应用 上架到 testFlight 闪退崩溃
    SQL面试题及答案
    滴滴 Redis 异地多活的演进历程
  • 原文地址:https://blog.csdn.net/weixin_44808225/article/details/133317762