将List转换成JSON字符串的问题


首先我有一个BOOK实体(对应数据的表),有两个外键,代码如下

   
  private Integer id;
  
private User user;//外键引用的对象
private Category category;//外键引用的对象
private String name;
private String press;
private String img;
private String phone;
private String price;
private String desc;

当book这个表只有一条纪录时,返回的Json字符串是这样的:

   
  [{"category":{"books":[{"$ref":"$[0]"}],"id":1,"name":"考证"},"desc":"23","id":3,"img":"onpath","name":"平凡的世界","phone":"12098","press":"路遥出息社","price":"298.3","user":{"books":[{"$ref":"$[0]"}],"createDate":"2015-03-13 00:00:00","id":1,"name":"jack","pwd":"e10adc3949ba59abbe56e057f20f883e"}}]
 

当book这个表有三条纪录时,返回的Json字符串是这样的:

   
  [{"category":{"books":[{"$ref":"$[0]"},{"category":{"$ref":"$[0].category"},"desc":"不要联系我 。","id":4,"img":"nopath","name":"困难的一生","phone":"122334","press":"科学出版社","price":"223.5","user":{"books":[{"$ref":"$[0]"},{"$ref":"$[0].category.books[1]"},{"category":{"$ref":"$[0].category"},"desc":"22234","id":5,"img":"345","name":"不要耍我","phone":"1222","press":"罢工出版社","price":"23","user":{"$ref":"$[0].category.books[1].user"}}],"createDate":"2015-03-13 00:00:00","id":1,"name":"jack","pwd":"e10adc3949ba59abbe56e057f20f883e"}},{"$ref":"$[0].category.books[1].user.books[2]"}],"id":1,"name":"考证"},"desc":"23","id":3,"img":"onpath","name":"平凡的世界","phone":"12098","press":"路遥出息社","price":"298.3","user":{"$ref":"$[0].category.books[1].user"}},{"$ref":"$[0].category.books[1]"},{"$ref":"$[0].category.books[1].user.books[2]"}]
 

将List转换成JSON字符串的代码以下:

   
  public void writeJSON(List list){
  
//用的是alibaba的JSON工具
String json = JSON.toJSONStringWithDateFormat(list,"yyyy-MM-dd HH:mm:ss");
ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
try {
ServletActionContext.getResponse().getWriter().write(json);
ServletActionContext.getResponse().getWriter().flush();
ServletActionContext.getResponse().getWriter().close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

请问为什么返回多条纪录的JSON字符串会出现这种情况,我需要每一个

   
  "user":{"books":[{"$ref":"$[0]"}],"createDate":"2015-03-13 00:00:00","id":1,"name":"jack","pwd":"e10adc3949ba59abbe56e057f20f883e"}}
 

都是这样的,而不是

   
  "user":{"$ref":"$[0].category.books[1].user"}}
 

的。

谢谢大家了!!

java json

咸腌蛋的超人 9 years, 8 months ago

Your Answer