-2
J'essaie de créer un service Web REST à l'aide de la classe Jersey ResourceConfig. Mais, j'obtiens une erreur, que je ne peux pas comprendre.Type de liste élément de discordance Objet
Incompatibilité de type: ne peut pas convertir type d'élément objet au produit
code:
@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));
}
}
La classe de produit:
@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;
}
}
N'utilisez pas de types bruts. Changer 'private static List productCatalog' à' private static Liste productCatalog' –
Eran
Merci. De plus j'ai changé la valeur de retour: return (Product []) products.toArray (new Product [products.size()]); – ESDEE