【发布时间】:2016-04-03 16:01:42
【问题描述】:
所以我在 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...
而postman中显示的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...
而且我无法弄清楚是什么原因造成的,以及为什么会发生这种情况。有什么建议吗?
【问题讨论】:
-
您可能需要向我们提供更多信息。我试过你的代码,它对我有用。
-
哦,我实际上知道为什么会发生这种情况(我编辑了上面的类并添加了一个 getResponseEntity 方法,这就是问题所在)...由于某种原因返回新的 ResponseEntity(this, HttpStatus .OK),导致无限递归。这是怎么回事?
-
因为它试图递归地序列化实体。要序列化对象,它必须从中获取所有属性,然后从其属性中获取所有属性,然后从其属性中获取所有属性,依此类推。而且因为属性之一是实体本身,所以这永远不会结束。
-
当时有没有其他方法可以做我想做的事情?
-
我不知道你想做什么:-)
标签: java json spring http spring-boot