Spring RestController忽略@ jsonProperty / JsonGetter / JsonSetter

时间:2019-09-24 21:52:25

标签: jackson spring-restcontroller

我正在使用Springboot 2.1.2.RELEASE。我有一个带有对象作为输入参数的get请求。期望类中的属性为请求参数。我的EmployeeBean在Java命名约定中具有属性。但是我需要自定义名称来请求参数。试图使用@ JsonProperty / @ Jsongetter / @JsonSetter批注来实现,但无法正常工作。我想念什么吗?

@RequestMapping(value="/api", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE )
public List<Map<String, Object>> getEmployeeData(EmployeeBean employeeBean


@Data
public class EmployeeBean implements Serializable {

private static final long serialVersionUID = -2757478480787308113L;

@JsonProperty(value="first_name")
private String firstName;

@JsonProperty(value="last_name")    
private String lastName;

1 个答案:

答案 0 :(得分:0)

尝试一下

    private String firstName;

    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @JsonProperty(value="first_name")
    public void setFirst_name(String firstName) {
        this.firstName = firstName;
    }

    @JsonProperty(value="last_name")
    public void setLast_name(String lastName) {
        this.lastName = lastName;
    }

控制器

@RestController
public class JsonController {

    @RequestMapping(value="/api", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE )
    public List<Map<String, Object>> getEmployeeData(EmployeeBean employeeBean) {
        System.out.println("employeeBean: "+employeeBean);
        return null;
    }
}

enter image description here

结果:

employeeBean: EmployeeBean [firstName=firstName10, lastName=lastName20]

我已经测试过并且有效

其他选项,在构造函数中使用JsonCreator:

    private String firstName;

    private String lastName;

    @JsonCreator
    public EmployeeBean(@JsonProperty("first_name") String first_name, @JsonProperty("last_name") String last_name) {
        this.firstName = first_name;
        this.lastName = last_name;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }