杰克逊序列化列表实体(将字段添加到根列表)

时间:2017-07-16 15:47:35

标签: java json jpa jackson wildfly

这是我的实体

@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持久性

返回的产品列表

2 个答案:

答案 0 :(得分:1)

您可以使用以下类来包含计数以及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;
    }
}

答案 1 :(得分:0)

具有泛型类型的类

public class ResultList<T> {

    private int count;
    @JsonProperty("results")
    private List<T> items;

    public List<T> getItems() {
        return items;
    }

    public void setItems(List<T> items) {
        this.items = Objects.requireNonNull(items, "items");
        this.count = items.size();
    }

    public int getCount() {
        return count;
    }
}

ProductResource

@GET
@Path(value = ApiConstant.Urls.PRODUCTS)
@Produces(value = MediaType.APPLICATION_JSON)
public ResultList getProducts(){
    List products = productService.findAll();
    ResultList result = new ResultList<Product>();
    result.setItems(products);
    return result;

}

谢谢@ ck1