2017-07-16 55 views
2

這是我的實體傑克遜序列化列表實體(加場到根目錄)

@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持續返回商品目錄

+1

您可以創建一個新的類'ProductsWrapper'與'count'和'results'然後在'getProducts'方法創建的這個實例,而是返回它的名單。 – tima

回答

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; 
    } 
} 
+0

太好了......感謝您的幫助 – Pako

0

類泛型type

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