Olá Pessol, estou tendo problemas ao tentar salvar um produto no banco de dados. Mais precisamente seria na formatação do JSON, estou utilizando uma API em Java com o Spring boot e no Front-end o Angular. Me parece que o Java espera um formato de JSON e Angular gera um outro. Deixarei aqui mais detalhes das classes do Back-end e do Front-end. Quem puder me ajudar serei grato desde já.
.*
O ERRO SERIE ESTE : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of loja.api.rest.model.Category
(although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)]
@Entity
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String price;
private String description;
private int quantity;
@ManyToOne
@JoinColumn(name = "category_id")
private Category category_id;
public Category getCategory_id() {
return category_id;
}
public void setCategory_id(Category category_id) {
this.category_id = category_id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
@Entity
public class Category implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
@RestController /* Arquitetura REST */
@RequestMapping(value = "/product")
public class ProductController {
@Autowired
private ProductRepository productRepository;
@PostMapping(value = "/", produces = "application/json")
@CachePut("cacheproduct")
public ResponseEntity<Product> cadastrarProduct(@RequestBody @Valid Product product) {
Product productSave = productRepository.save(product);
return new ResponseEntity<Product>(productSave, HttpStatus.OK);
}
```
Front-end: Angular
import { Category } from "./Category";
export interface CreateProductRequest {
name: string;
price: string;
description: string;
category_id: Category ;
quantity: number;
}
export interface Category{
id: number;
name: string;
}