Step 1 : Add below dependency in POM.xml
1 2 3 4 5 |
<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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
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.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….!!!