How To Convert Java Object To Json?

javatojson

Step 1 : Add below dependency in POM.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.3</version>
</dependency>

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.

package com.clarifyall.rest.controller;

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

import com.clarifyall.rest.model.UserBean;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;

@RestController
@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.setUserName("clarifyall.com");
		userBean.setAddress("AP");
		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 ClarifyAll.com. I am working in an IT professional.

View all posts by Manohar →

Leave a Reply