gpt4 book ai didi

java - Jackson 序列化列表实体(将字段添加到根列表)

转载 作者:行者123 更新时间:2023-11-30 10:27:46 24 4
gpt4 key购买 nike

这是我的实体

@Entity
public class Product extends AbstractBaseEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Type(type = "objectid")
private String id;
private String title;

我的资源

@Path(value = ApiConstant.Urls.PRODUCTS)
public class ProductResource {

@Inject
private ProductService productService;

@GET
@Path(value = ApiConstant.Urls.PRODUCTS)
@Produces(value = MediaType.APPLICATION_JSON)
public List getProducts(){
return productService.findAll();
}

我的 json 响应

[ {
"id" : "596b6a02f70a0878590bcf08",
"title" : "test1",
"description" : "description test 1"
}, {
"id" : "596b6b00f70a087b72d377eb",
"title" : "test1",
"description" : "description test 1"
}, {
"id" : "596b6b75f70a087d40f580d5",
"title" : "test1",
"description" : "description test 1"
} ]

我想创建一个计数字段来计算列表中的项目像这样并将列表添加到结果字段

{
"count": 3,
"results": [
{
"id" : "596b6a02f70a0878590bcf08",
"title" : "test1",
"description" : "description test 1"
}, {
"id" : "596b6b00f70a087b72d377eb",
"title" : "test1",
"description" : "description test 1"
}, {
"id" : "596b6b75f70a087d40f580d5",
"title" : "test1",
"description" : "description test 1"
} ],
}

我想序列化jpa持久化返回的Product List

最佳答案

您可以使用以下类来包含计数以及 Product 实体列表:

public class ResultList {
private int count;
@JsonProperty("results") private List<Product> products;

public List<Product> getProducts() {
return products;
}

public void setProducts(List<Product> products) {
this.products = Objects.requireNonNull(products, "products");
this.count = products.size();
}

public int getCount() {
return count;
}
}

关于java - Jackson 序列化列表实体(将字段添加到根列表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45130468/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com