I'm trying to create a simple REST service using Spring Web MVC and the JSON library https://mvnrepository.com/artifact/org.json/json/20210307. However, I've problems when passing data in JSON using POST, since Java raises an NullPointerException when the constructor of the data is invoked.
The REST controller that I created is this one:
@RestController @RequestMapping(path = "users/")
public class UserController {
@PostMapping(path = "/", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public String addUser(@RequestBody User user) {
return user.toString();
}
}
User class is defined in this way:
public class User extends Item implements Jsonable{
private String firstName;
private String lastName;
private LocalDate dateOfBirth;
private String taxCode;
private static int INCREMENTAL_ID = 0;
public User(String firstName, String lastName) {
super(INCREMENTAL_ID++);
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = LocalDate.now();
this.taxCode = this.generateTaxCode();
}
public String getFirstName() {
return firstName;
}
public void setFistName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = LocalDate.parse(dateOfBirth);
}
public String getTaxCode() {
return taxCode;
}
public void setTaxCode(String taxCode) {
this.taxCode = taxCode;
}
private String generateTaxCode() {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(this.getFirstName().toUpperCase().substring(0, 3))
.append(this.getLastName().toUpperCase().substring(0, 3))
.append(this.getDateOfBirth().toString())
.append((int)(Math.random()*100));
return strBuilder.toString();
}
@Override
public String toString() {
return super.toString() + " " + firstName + " " + lastName + " " + dateOfBirth
+ " " + taxCode;
}
@Override
public JSONObject toJson() {
return super.toJson().put("firstName", this.getFirstName())
.put("lastName", this.getLastName())
.put("dateOfBirth", this.getDateOfBirth().toString())
.put("taxCode", this.getTaxCode());
}
}
Then, passing the data in this way
{
"firstName": "Example",
"lastName": "Example"
}
The server raises the following error:
Constructor threw exception; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at ...User.generateTaxCode(User.java:61)
at ...User.<init>(User.java:24)
How can I pass data in a valid JSON format to the controller, is there any other Java Annotation in addUser method that makes this correctly?