I am creating an API to simulate a vending machine and I'm using Spring, JPA and MySQL. I have an endpoint for a POST request that allows for new user creation by entering the user's details into a table called users however, I am having trouble deserializing the JSON from the request to an enum. None of the solutions I have found online have worked including all of the deserialization solutions involving annotations that can be found here https://www.baeldung.com/jackson-serialize-enums.
This is the exception message I get when making a POST request using Postman:
2023-01-21T02:50:05.712Z WARN 9544 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: No enum constant com.vendingmachine.springboot.utils.Role.buyer]
When I have the role
as BUYER
in the POST request, it works fine but I want it to be case insensitive.
User class:
@Entity
@Table(name = "users")
public class User
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int userId;
@NotNull
@Column(name = "username", unique = true)
private String username;
@NotNull
@Column(name = "password")
private String password;
@NotNull
@Column(name = "role")
private Role role;
@NotNull
@Column(name = "deposit")
private BigDecimal deposit;
public User() {}
public User(String username, String password, Role role, BigDecimal deposit)
{
this.username = username;
this.password = password;
this.role = role;
this.deposit = deposit;
}
public int getId()
{
return userId;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public Role getRole()
{
return role;
}
public void setRole(String role)
{
this.role = Role.valueOf(role);
}
public void setRole(Role role) {
this.role = role;
}
public BigDecimal getDeposit()
{
return deposit;
}
public void setDeposit(BigDecimal deposit)
{
this.deposit = deposit;
}
}
Role enum:
public enum Role
{
BUYER("buyer"),
SELLER("seller");
private final String role;
Role(String role)
{
this.role = role;
}
public String getRole()
{
return role;
}
public static Role getRoleEnum(String roleString)
{
return switch (roleString.toLowerCase()) {
case "buyer" -> Role.BUYER;
case "seller" -> Role.SELLER;
default -> throw new IllegalArgumentException("Role [" + roleString
+ "] not supported.");
};
}
}