问题:解决sprigboot项目get请求中有下划线的入参参数,如:first_name,希望在项目中将下划线格式转成firstName,用@JsonProperty注解发现失效问题
1.核查:@JsonProperty注解对应包是否正确
正确包:import com.fasterxml.jackson.annotation.JsonProperty;
如果使用jar正确,还是无效,往下看
2.在实体类中重写参数的set方法
例子:
实体类:
package com.iterge.lph_test.entity;
import lombok.AccessLevel;
import lombok.Data;
import lombok.experimental.FieldDefaults;
/**
* Create by LPH 2021/8/3
*/
@Data
@FieldDefaults(level = AccessLevel.PRIVATE)
public class UserReq {
Long id;
String name;
String firstName;
}
Controller:
package com.iterge.lph_test.controller;
import com.iterge.lph_test.entity.UserReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author liuph
* @date 2023/8/10 15:01:30
*/
@RestController
@RequestMapping("/test")
@Slf4j
public class ParamController {
@GetMapping("/param/test")
public String params(UserReq req){
log.info("入参数:{}",req);
return req.toString();
}
}
结果:
修改后:
实体类:
package com.iterge.lph_test.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AccessLevel;
import lombok.Data;
import lombok.experimental.FieldDefaults;
/**
* Create by LiuPH 2021/8/3
*/
@Data
@FieldDefaults(level = AccessLevel.PRIVATE)
public class UserReq {
Long id;
String name;
@JsonProperty("first_name")
String firstName;
public void setFirst_name(String name){
this.firstName = name;
}
}
运行结果:
over~