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.

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

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;
public class EmployeeController {

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

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