我尝试使用Jersey ResourceConfig类创建REST Web服务。
但是,我收到了一个错误,我无法理解。
类型不匹配:无法从元素类型对象转换为产品
代码:
@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;
}
}
答案 0 :(得分:0)
似乎你没有写出列表类型。
private static List<Product> productCatalog;