我正在用Spring创建RESTful WS。现在,对于每个WS,我都会为几个对象创建新的类。对于端点,我将这些类用作请求数据,而Jackson会自动将其转换,但是如果我只想将该对象的几个字段用于另一个端点,该怎么办?我不想为此创建另一个类。
例如,我有一个模型:
public class Salary {
/*
* Request Params
*/
@JsonProperty("ID")
private String documentId;
@JsonProperty("DOCUMENTDATE")
private Date createdDate;
@JsonProperty("DOCUMENTNUMBER")
private String documentNumber;
@JsonProperty("PAYERACCOUNT")
private String payer;
@JsonProperty("RECEIVERACCOUNT")
private String receiver;
@JsonProperty("AMOUNT")
private Double amount;
@JsonProperty("CURRCODE")
private String currency;
@JsonProperty("GROUND")
private String ground;
/* Getters & Setters */
// etc
}
终点:
@PostMapping("salaries")
public Response createSalary(@RequestBody Salary salary) {
return salaryManager.createSalary(salary);
}
// There I want to use not the whole fields of Salary, but only documentDate and documentNumber
@PostMapping("salaries/transfer")
public Response transferSalary(@RequestBody Salary salary) {
return salaryManager.transferSalary(salary);
}
因此,在上面的示例中,我在第二个端点中仅接受Salary类的少数几个参数作为请求。
答案 0 :(得分:1)
假设您具有以下json,并且您不希望电机具有所有属性,
{
"name": "kia",
"motor": {
"created_date": "2017-01-01",
"size": "1L",
"power": "44kw",
},
"model": "rio",
"country": "south korea",
"currency": "USD",
"price": "14000"
}
您可以将DTO中的motor属性建模为String,例如:
public class Car {
public String name;
// define the attribute, that you want to save flat as a String.
private String motor;
//or define specific attributes of the motor, that you want to parse.
private String motorPower;
// use the map as input and parse only the attributes that you need.
@JsonProperty("motor")
public String parseMotorAttributes(Map<String,Object> motorInfo) {
StringBuilder sb = new StringBuilder();
sb.append("size: ")
.append((String)motorInfo.get("size"));
this.motor = sb.toString();
//set the concrete attributes you defined
this.motorPower = (String)motorInfo.get("power");
return this.motor;
}
public String country;
public String currency;
public String price;
}
答案 1 :(得分:0)
我不知道这是一个合适的解决方案,但是我只是希望像往常一样在请求中找到相同的对象,然后我只是验证所需的字段而已。