【问题标题】:How to use only several fields of object for REST service如何仅将对象的几个字段用于 REST 服务
【发布时间】:2019-01-30 19:22:28
【问题描述】:

我正在使用 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 类的几个参数作为请求。

【问题讨论】:

  • 请问如果设置 RequestBody(required=false) 会发生什么?
  • @EiriniGraonidou 其实没什么,同样的行为。

标签: java spring rest jackson


【解决方案1】:

假设您有以下 json,并且您不想要电机的每个属性,

 { 
       "name": "kia",
       "motor": {
          "created_date": "2017-01-01",
          "size": "1L",
          "power": "44kw",
       },
       "model": "rio",
       "country": "south korea",
       "currency": "USD",
       "price": "14000"
 }

您可以将 DTO 中的电机属性建模为字符串,例如:

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;

}

【讨论】:

  • @catscoolzhyk 我认为在你编辑你的问题之后,这个答案是断章取义的。你同意吗?
  • 是的,我同意 =) 无论如何对我来说这是有用的信息
【解决方案2】:

我不知道这是不是一个合适的解决方案,但我所做的只是像往常一样期望请求中的相同对象,然后我只是验证所需的字段就是这样。

【讨论】:

    猜你喜欢
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 2014-12-31
    • 2017-09-01
    相关资源
    最近更新 更多