所以我在java spring中有一个简单的方法,它返回一个类作为ResponseBody:
@RequestMapping(value = "update", method = RequestMethod.PUT)
public @ResponseBody JKResponse update() {
return new JKResponse();
}
JKResponse类如下:
@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);
}
}
但是当我使用邮递员调用“更新”API路由时,我收到以下错误:
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...
邮递员中显示的JSON是:
{"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...
我无法弄清楚造成这种情况的原因,以及为什么会这样。有什么建议吗?
答案 0 :(得分:0)
您通常不需要向用户发送ResponseEntity,ResponseEntity是您用来告诉Spring应该返回给用户的数据对象。它应该像这样使用:
@RequestMapping(value = "update", method = RequestMethod.PUT)
public ResponseEntity<JKResponse> update () {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Boiling", "True");
return new ResponseEntity<JKResponse>(
new JKResponse(), responseHeaders, HttpStatus.I_AM_A_TEAPOT);
}
用户将得到这个:
$ curl -X PUT -i 127.0.0.1:8080/update
HTTP/1.1 418
Server: Apache-Coyote/1.1
Boiling: True
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Tue, 29 Dec 2015 20:03:51 GMT
{"stuff":[]}