How To Convert Java Object To Json?


Step 1 : Add below dependency in POM.xml


Note : If you are using Spring Boot application above dependency available inside ,no need to add externally.

Step 2 : Use below code for converting the Java object to Json.


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;

@RequestMapping(path = "/rest")
public class JavaToJsonController 
    @GetMapping(path="/getJson", produces = "application/json")
    public String getjson() throws JsonProcessingException 
    	UserBean userBean=prepareUserBean();
		ObjectWriter ow = new ObjectMapper().writer();
		String json = ow.writeValueAsString(userBean);
		return json;
    public UserBean prepareUserBean() {
    	        UserBean userBean = new UserBean();
		userBean.setEmail("[email protected]");
		userBean.setPhoneNo("+91 9678554455");
		return userBean;

Example Application :

Point 1 : Download below spring boot example source code.

Point 2 : Import Source code in Eclipse.

Point 3 : Do the Maven clean, Project clean and Maven build.

Point 4 : Test the application as below.

End Point URL : http://localhost:8080/rest/getJson

Method Type : GET

Please download source using below link….!!!

About Manohar

I, Manohar am the founder and chief editor of I am working in an IT professional.

View all posts by Manohar →

Leave a Reply