Today we will see how to return object from controller as JSON response. It's pretty simple. What all you need to do is follow the below steps :-
Step-1: First, We will create a default project starter package will be used for "main" class container. Please note going forward this package and ProjectStarter.java class will be used for main class. Now you would need to copy and paste the below code.
package com.ncteam.projectstarter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import com.ncteam.firstapplication.FirstApplication;
@SpringBootApplication
@ComponentScan(basePackages = { "com.ncteam"} )
public class ProjectStater {
public static void main(String[] args) {
SpringApplication.run(ProjectStater.class, args);
}
}
Your Project structure should look like below image -
Step-2 : Now create the controller class (ReturnObjectFromController and ListPojo) in a different package (com.ncteam.secondtutorial). ListPojo class is basically a pojo class will have all the objects getter-setters.
Below code is for ListPojo.java
package com.ncteam.secondtutorial;
public class ListPojo {
private String emplId;
private String name;
private String address;
public ListPojo() {
}
public ListPojo(String emplId, String name, String address) {
super();
this.emplId = emplId;
this.name = name;
this.address = address;
}
public String getEmplId() {
return emplId;
}
public void setEmplId(String emplId) {
this.emplId = emplId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Below code is for the controller class (ReturnObjectFromController.java)
package com.ncteam.secondtutorial;
import java.util.Arrays;
import java.util.List;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ReturnObjectFromController {
@RequestMapping("/listofpojo")
public List<ListPojo> sayHello() {
return Arrays.asList( new ListPojo("Emp1","Kennith", "NJ"),
new ListPojo("Emp2","Jorge", "NC"),
new ListPojo("Emp1","Melanie", "NY"));
}
}
Project structure should look like below image-
Step-3: That's all we are all good to run the project. Run the project as I have explained in previous tutorial and test the change in the below URL - http://localhost:8080/listofpojo
If you have followed all the above steps perfectly - we should be able to see the output like below screen-
Please Donate Us @ https://imjo.in/t9cEFy
No comments:
Post a Comment