简体   繁体   中英

Spring MVC @ResponseBody return list is not proper json reponse using hibernate

Spring MVC @ResponseBody return list is not proper json reponse(no key & brace brackets) while using hibernate but getting proper json response if not using hibernate.

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(I am getting)

[[1,"pratyush","pratyush.ankit@gmail.com"]]

But I need response like below :

[{"id":1,"name":"Pratyush","email":"pratyush.ankit@gmail.com"}]

You should change your DAO function to:

public List<Student> getStudentData(){
    String hql = "from Student";
    Query query =  sessionFactory.getCurrentSession().createQuery(hql);
    List<Student> list = query.list();
    return list;
}

The way you defined the hql query, it would return List of arrays in a form of [id, name, email]. And it would be impossible to convert it to a proper json later (the labels would be lost by that point). What you want is to make getStudentData() return List of Student objects instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM