相同的用户dto,但两个服务使用不同的JsonProperty

时间:2017-11-20 04:14:49

标签: java json spring rest

我有两个Spring Rest服务创建员工创建员工,如下所示

创建-雇员

@RequestMapping(value="/create-employee", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Void> createEmployee(final @RequestBody User user) {
    try {
        // employee createion logic
    } catch (Exception exception) {
        log.error("Exception in createEmployee:"+exception.getMessage());
        return new ResponseEntity<>(HttpStatus.FORBIDDEN);
    }
}

创建员工

@RequestMapping(value="/create-staff", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Void> createStaff(final @RequestBody User user) {
    try {
        // staff creation logic
    } catch (Exception exception) {
        log.error("Exception in createStaff:"+exception.getMessage());
        return new ResponseEntity<>(HttpStatus.FORBIDDEN);
    }
}

对于我使用名为User的dto的两种服务,如下所示:

public class User {
    @JsonProperty("employeeName")
    private String name;

    @JsonProperty("age")
    private Integer age;

    @JsonProperty("managerName")
    private String headName;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getHeadName() {
        return headName;
    }

    public void setHeadName(String headName) {
        this.headName = headName;
    }
}

现在问题在于 create-employee create-staff ,因为我使用 User.java 作为请求正文。发布json正文看起来像这样

{
 "employeeName" : "string",
 "age" : "integer",
 "managerName" : "string"
}

但实际上我想要的是创建员工服务我希望json主体如下所示

{
 "staffName" : "string",
 "age" : "integer",
 "managerName" : "string"
}

创建员工服务我想将json正文如下所示

{
 "employeeName" : "string",
 "age" : "integer",
 "managerName" : "string"
}

但对于这两项服务,我需要使用相同的 User.java dto,但两种服务使用不同的JsonProperty

任何人都可以请我这个

1 个答案:

答案 0 :(得分:0)

杰克逊还支持JsonAlias,这可能会对您有所帮助,只需确保您将jacskon映射器更新为版本2.9.1

public class User {
    @JsonAlias({"employeeName","staffName"})
    private String name;

    @JsonProperty("age")
    private Integer age;

    @JsonProperty("managerName")
    private String headName;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getHeadName() {
        return headName;
    }

    public void setHeadName(String headName) {
        this.headName = headName;
    }
}