Spring MVC @ResponseBody返回列表在使用休眠模式时不是正确的json响应(没有键和大括号),但是如果不使用休眠则获得正确的json响应。
道
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;
}
控制者
@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()
返回List
个对象的Student
。