[英]How to print List() in @RestController Response?
I've a controller in a Spring App with this Code: 我在Spring App中有一个使用以下代码的控制器:
@RequestMapping("/")
@ResponseBody
public ResponseObject index(){
System.out.println(this.sf);
Session session = sf.openSession();
List<Project> projects = session.createQuery("from Project").list();
session.close();
System.out.println(projects);
return new ResponseObject(projects);
}
I've tried to return List<Project>
and also my new created Object ResponseObject
with this code: 我试图用以下代码返回
List<Project>
以及我新创建的Object ResponseObject
:
public class ResponseObject {
protected Object data;
protected Object error;
public ResponseObject(Object data) {
this.data = data;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Object getError() {
return error;
}
public void setError(Object error) {
this.error = error;
}
}
But in all cases my JSON Reponse looks like: {"data":[{}],"error":null}
. 但是在所有情况下,我的JSON Reponse都看起来像:
{"data":[{}],"error":null}
。
Projects
output is : [Project{id=1, name='Digital project'}]
Projects
输出为: [Project{id=1, name='Digital project'}]
Can anybody tell me why my List is not included in the JSON? 谁能告诉我为什么我的列表未包含在JSON中? Thanks!
谢谢!
protected Object data;
改成
protected List<Object> data;
You need to return a ResponseEntity like : 您需要返回一个ResponseEntity,如:
return new ResponseEntity<List<Project>>(projects, HttpStatus.OK);
see http://docs.spring.io/autorepo/docs/spring/4.0.2.RELEASE/javadoc-api/org/springframework/http/ResponseEntity.html 参见http://docs.spring.io/autorepo/docs/spring/4.0.2.RELEASE/javadoc-api/org/springframework/http/ResponseEntity.html
Provided you have Jackson in the classpath, which if you're using Spring boot you do everything will be de-serialized correctly. 如果您在类路径中有Jackson,那么如果您使用的是Spring boot,则可以正确地反序列化所有操作。 You do not need the ResponseObject class.
您不需要ResponseObject类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.