是否可以输出Entity ShoppingCart的返回值totalAmount,它不是Class中的Value而是Method?例如,我有一个带有项目列表的Class Shoppingcart。和方法totalAmount。现在,当我使用网址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?
答案 0 :(得分:0)
是的,您可以通过使用Jackson @JsonProperty注释
注释您的方法来实现这一目标代码示例
@JsonProperty("totalAmount")
public double computeTotalAmount()
{
// compute totalAmout and return it
}
答案 1 :(得分:0)
并在阅读完之后回答下一个问题。如何计算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"
}
}
}
希望它可以帮到你:)