javajsonspring-bootserializationjson-deserialization

JSON parse error: Cannot construct instance: no int/Int-argument constructor/factory method to deserialize from Number value


I am trying to insert user record using mysql database

Customer.java

@Entity
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String firstname;
    private String lastname;
    @Column(unique = true)
    private String email;
    @Column(nullable = false)
    private String password;
    @Column(unique = true, nullable = false)
    private String username;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "user_roles",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id"))
    private List<Role> roles;
}

CustomerController

    @PostMapping("/customer")
    public void addCustomer(@RequestBody Customer customer) {
        customerService.createCustomer(customer);
    }

CustomerService

@Service
public class CustomerService {
    public CustomerService(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }

    public void createCustomer(Customer customer) {

        customerRepository.save(customer);
    }
}

Role.java

public class Role {

    @Id
    private Long id;

    private String name;

    @ManyToMany(mappedBy = "roles")
    private Set<Customer> customers;
}

JSON Ojbect

{
  "firstname": "John",
  "lastname": "Doe",
  "email": "John@example.com",
  "password": "john",  // Ensure that passwords are hashed and never stored in plain text
  "username": "john123",
  "roles" : [1]
}

Solution

  • The JSON object provided in your request should correctly map to the Role entity(It has id, name properties).

    If you want to pass roles as objects, then the JSON should be this,

    {
      "firstname": "John",
      "lastname": "Doe",
      "email": "john@example.com",
      "password": "john",  // Ensure that passwords are hashed and never stored in plain text
      "username": "john123",
      "roles" : [
        {"id": 1, "name": "ROLE_USER"}
      ]
    }