How to convert object to Json in Spring MVC

To convert Object to JSON you need Gson jar to add to WEB-INF/lib directory and use @ResponseBody annotation for the json output.

Download gson.jar from here gson.jar.

Methods of Gson

  • toJson(Object) : It converts Object to Json String.
  • fromJson(String): It convert Json String to Object.

We can use this for REST web services also. Please see below the following controller.

Employee.java


package com.startwithjava.beans;
class Employee{
public String name;
public double salary;
public Employee(String name,double salary){
this.name=name;
this.salary=salary;
}
public String getName(){
 return name;
}
public void setName(){
this.name=name;
}
public double getSalary(String name){
 return Salary;
}
public void setSalary(double salary){
this.salary=salary;
}
}

EmployeeController.java


package com.startwithjava.controllers;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
@Controller
public class EmployeeController {

/**
* This method invokes for fetches employee data for edit form
*/
@Autowired
EmployeeDao dao;

@RequestMapping(value="/employee/edit",method=RequestMethod.POST)
@ResponseBody
public String editEmployee(HttpServletRequest request){
int id     = Integer.parseInt(request.getParameter("id"));
Employee e = dao.getEmployee(id);
Gson gson = new Gson();
//Here object is converted to json string
String json = gson.toJson(e);
return json;
}
}

Leave a Reply