Spring MVC @ResponseBody 返回列表在使用 hibernate 时不是正确的 json 响应(没有键和大括号),但如果不使用 hibernate 则获得正确的 json 响应。
DAO
public List getStudentData(){
String hql= "select s.id, s.name, s.email from Student s";
Query query= sessionFactory.getCurrentSession().createQuery(hql);
List list= query.list();
return list;
}
Controller
@RequestMapping(value="/fetchAllData" , method=RequestMethod.GET)
public @ResponseBody List studentContainer1(HttpServletRequest response){
return ss.getStudentData();
}
JSON(我正在获取)
[[1,"pratyush","pratyush.ankit@gmail.com"]]
但我需要如下回复:
[{"id":1,"name":"Pratyush","email":"pratyush.ankit@gmail.com"}]
最佳答案
您应该将 DAO 函数更改为:
public List<Student> getStudentData(){
String hql = "from Student";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
List<Student> list = query.list();
return list;
}
按照您定义 hql 查询的方式,它将以 [id, name, email] 的形式返回数组的 List
。并且稍后不可能将其转换为正确的 json(此时标签将丢失)。您想要的是让 getStudentData()
返回 Student
对象的 List
。
关于java - Spring MVC @ResponseBody 返回列表不是使用 hibernate 的正确 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39555368/