Spring REST JSON Post Example

In this tutorial, we will see How to post JSON object in post requests.  You can access Spring REST Maven Tutorial for beginners here.

This tutorial provides sample code Spring REST JSON pojo example: Hope you have already configured Spring REST project setup:

Sample JSON object:

suppose let’s consider the below JSON sample that need to post

{
“studentId”: 30303,
“name”: “Javasavvy”,
“description”: “Spring REST Annotation tutorial”
}

 Java POJO:

Create Student.java pojo and add the below varaibles

public class Student {

 private long studentId;
 private String name;
 private String description;
 public long getStudentId() {
 return studentId;
 }
 public void setStudentId(long studentId) {
 this.studentId = studentId;
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public String getDescription() {
 return description;
 }
 public void setDescription(String description) {
 this.description = description;
 }
   
}

Spring REST Controller Method:

Create StudentController class and add addStudent method.  Set method as POST in @RequestMapping Annotation.  In the parameters, add @RequestBody Student object. Student object must be converted to JSON and with  Spring’s HTTP message converter support, we no need to do this conversion manually.

Spring uses  Jackson 2 and MappingJackson2HttpMessageConverter is will do POJO to JSON and JSON to POJO  automatically. Make sure that Jackson is added in the class path library.

 

@Controller
@RequestMapping("/student")
public class StudentController {

  @RequestMapping(value="/add-student",method=RequestMethod.POST,consumes =
 {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE},
 produces={MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_JSON_VALUE})
 public @ResponseBody Student addProduct(@RequestBody Student st){
  System.out.println("pr"+st.getName());
 return st;
 }
}

You can use SOAP REST UI client to test:

Spring REST JSON Post tutoria
Spring REST JSON Post tutoria

Download sample code here:  Click here to download spring rest json example with maven