title: How to convert list of Objects to JSON in Spring MVC and Hibernate?
body: <p>I'm Using Spring MVC and hibernate to fetch data from MySQL. In the controller class a ModelAndView method listEmployees is returning a MAP.The method is getting list of Employee objects from EmployeeService class. I want this method to take list of Employee Objects from Service class and covert it into JSON,or convert it into JSON and write that data in a JSON file so that I can use this JSON data in a JSP page.</p>
  
  <pre><code>@RequestMapping(value="/employees", method = RequestMethod.GET)  
   public @ResponseBody ModelAndView listEmployees() {  
    Map&lt;String, Object&gt; model = new HashMap&lt;String, Object&gt;();
    model.put("employees",prepareListofBean(employeeService.listEmployeess()));  
    return new ModelAndView("employeesList", model);  
  
   }
  
  private List&lt;EmployeeBean&gt; prepareListofBean(List&lt;Employee&gt; employees){
          List&lt;EmployeeBean&gt; beans = null;
          if(employees != null &amp;&amp; !employees.isEmpty()){
              beans = new ArrayList&lt;EmployeeBean&gt;();
              EmployeeBean bean = null;
              for(Employee employee : employees){
                  bean = new EmployeeBean();
                  bean.setName(employee.getEmpName());
                  bean.setId(employee.getEmpId());
                  bean.setAddress(employee.getEmpAddress());
                  bean.setSalary(employee.getSalary());
                  bean.setAge(employee.getEmpAge());
                  beans.add(bean);
              }
          }
          return beans;
      }
  </code></pre>
  
  <p><strong>EDIT</strong></p>
  
  <p>In this below method I tried GSON to convert list to JSON,but was getting null pointer Exception. </p>
  
  <pre><code>**@RequestMapping(value="/employees1", method = RequestMethod.GET)  
      public ModelAndView employeelist() {  
  
      Gson gson=new Gson();
      gson.toJson(employeeService.listEmployeess());
  
      ModelAndView modelAndView=new ModelAndView();
      modelAndView.addObject(gson);
  
      return modelAndView;
  
      }**
  </code></pre>
  
  <p><strong><em>What could be the mistake in this above method?</em></strong></p>