2017-10-10 48 views
-2

我正在嘗試使用Jersey ResourceConfig類創建REST webservice。列表類型不匹配元素對象

但是,我收到一個錯誤,我不明白。

類型不匹配:不能從元素類型的對象轉換爲產品

代碼:

@Path("productcatalog") 
public class ProductCatalogResource { 
    private static List productCatalog; 
    public ProductCatalogResource() { 
     initializeProductCatalog(); 
    } 
    @GET 
    @Path("search/category/{category}") 
    @Produces(MediaType.APPLICATION_JSON) 
    public Product[] searchByCategory(@PathParam("category") String category) { 
     List products = new ArrayList(); 
     for (Product p : productCatalog) { // OBJECT TYPE ERROR 
      if (category != null && category.equalsIgnoreCase(p.getCategory())) { 
       products.add(p); 
      } 
     } 
     return products.toArray(new Product[products.size()]); // OBJECT TYPE ERROR 
    } 

    private void initializeProductCatalog() { 
     if (productCatalog == null) { 
      productCatalog = new ArrayList(); 
      productCatalog.add(new Product(id, name, category, unitPrice)); 
    } 
} 

產品類:

@XmlRootElement 
public class Product implements Serializable { 
    private int id; 
    private String name; 
    private String category; 
    private double unitPrice; 

    public Product() {} // needed for JAXB 
    public Product(int id, String name, String category, double unitPrice) { 
     this.id = id; 
     this.name = name; 
     this.category = category; 
     this.unitPrice = unitPrice; 
    } 
} 
+3

請勿使用原始類型。將'private static List productCatalog'更改爲'private static List productCatalog' – Eran

+0

謝謝。此外,我更改了返回值:return(Product [])products.toArray(new Product [products.size()]); – ESDEE

回答

0

看來,你沒有寫列表類型。

private static List<Product> productCatalog; 
相關問題