是否可以输出一个实体totalAmount的返回值ShoppingCart,它不是类中的值,而是一个方法?例如,我有一个带有项目列表的类Shoppingcart。以及一种方法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"
}
}
}有什么注释能做这件事还是别的什么吗。我试图将其添加到(org.springframework.hateoas.ResourceProcessor)中,但只有添加额外链接的可能性。还是我需要添加一个类值totalAmount?
发布于 2016-12-07 10:40:55
是的,您可以通过用Jackson @JsonProperty注释注释您的方法来实现这一点。
代码样本
@JsonProperty("totalAmount")
public double computeTotalAmount()
{
// compute totalAmout and return it
}发布于 2016-12-07 22:44:08
为了回答下一个可能的问题,你在阅读完这篇文章后会得到一个答案。如何计算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"
}
}
}希望它能帮助你:)
https://stackoverflow.com/questions/41014966
复制相似问题