So I have a simple method in java spring that returns a class as a ResponseBody:
@RequestMapping(value = "update", method = RequestMethod.PUT)
public @ResponseBody JKResponse update() {
return new JKResponse();
}
And the JKResponse class is as follows:
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY,
isGetterVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.ANY)
public class JKResponse implements Serializable {
static final long serialVersionUID = 1L;
@JsonProperty
private List<String> stuff;
public JKResponse() {
this.stuff = new ArrayList<String>();
}
public void setStuff(final List<String> stuff) {
this.stuff = stuff;
}
public List<String> getStuff() {
return this.stuff;
}
/*
THIS METHOD IS CAUSING THE INFINITE RECURSION, BUT WHY?
*/
public ResponseEntity<JResponse> getResponseEntity() {
return new ResponseEntity<JResponse>(this, HttpStatus.OK);
}
}
But when I use postman to called the "update" API route, I get the following error:
Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Infinite recursion (StackOverflowError) (through reference chain: org.springframework.http.ResponseEntity["body"]->com.proj.services.JKService["responseEntity"]->org.springframework.http.ResponseEntity["body"] and so on...
And the JSON displayed in postman is:
{"responseEntity":{"headers":{},"body":{"responseEntity":{"headers":{},"body":{"responseEntity":{"headers":{},"body":{"responseEntity":{"headers":{},"body":{"responseEntity":{"headers":{},"body":{"responseEntity":{"headers":{},"body":{"responseEntity":{"headers":{},"body":{"responseEntity":{"headers":{},"body":{"responseEntity":{"headers":{},"body":{"responseEntity":{"headers":{},"body":{"responseEntity":{"headers":{},"body":{"responseEntity":{"headers":{},"body":{"responseEntity":{"headers":{},"body":{"responseEntity":{"headers":{},"body":{"responseEntity":{"headers":{},"body": and so on...
And I can't figure out what is causing this, and why this is happening. Any advice?
You don't usually need to send ResponseEntity to the user, ResponseEntity is the data object you use to tell Spring what it should return to the user. It is supposed to be used like this:
And the user will get this: