I'm developing a simple project using Java Spark, and at the moment I'm trying to implement a little RESTful service. I have this post method:
post("/users", (request, response) -> {
response.type("application/json");
User user = new Gson().fromJson(request.body(),User.class);
userService.addUser(user);
return new Gson().toJson(response);
});
I'm using postman to specify the body of the request:
{ "id": "1012",
"name": "Mac",
"lastname": "Mason1",
"email": "email"
}
And the User class is:
public class User {
public int id;
public String name;
public String lastname;
public String email;
public User (int id, String name, String lastname, String email) {
this.id = id;
this.name = name;
this.lastname = lastname;
this.email = email;
}
Whenever I try to do a post request, the following error pops up:
ERROR spark.http.matching.GeneralError -
java.lang.IllegalArgumentException: class
org.eclipse.jetty.server.handler.ErrorHandler declares multiple JSON fields
named _listeners
return new Gson().toJson(response);
This code is trying to serialize the response
object as JSON. This is probably a typo (surely you meant return new Gson().toJson(user);
, or something entirely different instead) and fails because of the way Gson tries to recursively serialize all fields in the class hierarchy of response
.