如何在 Spring Rest Entity 中输出诸如 totalAmount 之类的方法的 return 值

How can I output the return value of a Method like totalAmount in an Spring Rest Entity

是否可以输出实体购物车的 return 值 totalAmount 不是 Class 中的值而是方法?因此,例如,我有一个 Class 购物车,其中包含一个项目列表。和一个方法 totalAmount。现在,当我使用 URL http://localhost:8082/carts/1 向 API 发出请求时,我希望得到如下响应:

{ 
"creationDate": "2016-12-07T09:45:38.000+0000",
  "items": [
    {
      "itemName": "Nintendo 2DS",
      "description": "Konsole from Nintendo",
      "price": 300.5,
      "quantity": 3
    },
    {
      "itemName": "Nintendo Classic",
      "description": "Classic nintendo Console from the 80th...",
      "price": 75,
      "quantity": 2
    }
  ],
  "totalAmount": "1051,50",
  "_links": {
    "self": {
      "href": "http://localhost:8082/carts/2"
    },
    "cart": {
      "href": "http://localhost:8082/carts/2"
    },
    "checkout": {
      "href": "http://localhost:8083/order"
    }
  }
}

目前 API 请求的响应如下所示:

{
  "creationDate": "2016-12-07T09:45:38.000+0000",
  "items": [
    {
      "itemName": "Nintendo 2DS",
      "description": "Konsole from Nintendo",
      "price": 300.5,
      "quantity": 3
    },
    {
      "itemName": "Nintendo Classic",
      "description": "Classic nintendo Console from the 80th...",
      "price": 75,
      "quantity": 2
    }
  ],
  "_links": {
    "self": {
      "href": "http://localhost:8082/carts/2"
    },
    "cart": {
      "href": "http://localhost:8082/carts/2"
    },
    "checkout": {
      "href": "http://localhost:8083/order"
    }
  }
}

是否有注释可以完成这项工作或其他工作。我试图将其添加到 CartResourceProcessor (org.springframework.hateoas.ResourceProcessor) 中,但只能添加其他链接。或者我是否需要添加一个 Class 值 totalAmount?

是的,您可以通过使用 Jackson @JsonProperty 注释对您的方法进行注释来实现这一点

代码示例

@JsonProperty("totalAmount")
public double computeTotalAmount()
{
    // compute totalAmout and return it
}

并回答您阅读本文后可能遇到的下一个问题。如何计算 totalAmount。这里是片段

public Class Cart{
   // some Class values

   @JsonProperty("totalAmount")
   public BigDecimal total(){

        return items.stream()
                .map(Item::total)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}

public class Item{
     // some Item values

     @JsonProperty("totalAmount")
     public BigDecimal total(){
         return price.multiply(new BigDecimal(this.quantity));
     }
}

输出类似这样的东西:

{
  "creationDate": "2016-12-07T09:45:38.000+0000",
  "items": [
    {
      "itemName": "Nintendo 2DS",
      "description": "Konsole from Nintendo",
      "price": 300.5,
      "quantity": 3,
      "totalAmount": 901.5
    },
    {
      "itemName": "Nintendo Classic",
      "description": "Classic nintendo Console from the 80th...",
      "price": 75,
      "quantity": 2,
      "totalAmount": 150
    }
  ],
  "totalAmount": 1051.5,
  "_links": {
    "self": {
      "href": "http://localhost:8082/carts/2"
    },
    "cart": {
      "href": "http://localhost:8082/carts/2"
    },
    "checkout": {
      "href": "http://localhost:8083/order"
    }
  }
}

希望对你有帮助:)