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

先粘贴问题代码

entity类

@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class EyeRequest extends CommonRequest {

    private Integer PRECLOSE;

    private Integer MDEC;

    private Integer BF;

    private Integer MAR;

    public EyeRequest(Integer timestamp, Integer PRECLOSE, Integer MDEC, Integer BF, Integer MAR) {
        super(ResponseConstant.EYE_TYPE, timestamp);
        this.PRECLOSE = PRECLOSE;
        this.MDEC = MDEC;
        this.BF = BF;
        this.MAR = MAR;
    }
}

controller类

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

请求的body

{
    "PRECLOSE": 1,
    "MDEC": 1,
    "BF": 1,
    "MAR": 1,
    "timestamp": 1111
}

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

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

@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class EyeRequest extends CommonRequest {

    @JsonProperty(value = "PRECLOSE")
    private Integer preclose;

    @JsonProperty(value = "MDEC")
    private Integer mdec;

    @JsonProperty(value = "BF")
    private Integer bf;

    @JsonProperty(value = "MAR")
    private Integer mar;

    public EyeRequest(Integer timestamp, Integer preclose, Integer mdec, Integer bf, Integer mar) {
        super(ResponseConstant.EYE_TYPE, timestamp);
        this.preclose = preclose;
        this.mdec = mdec;
        this.bf = bf;
        this.mar = mar;
    }
}

重新启动后可以成功赋值

Logo

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

更多推荐