2
2
.
.
1
1
1
1
.
.
5
5
F
F
r
r
o
o
m
m
J
J
S
S
O
O
N
N
-
-
@
@
R
R
e
e
q
q
u
u
e
e
s
s
t
t
B
B
o
o
d
d
y
y
-
-
P
P
r
r
o
o
p
p
e
e
r
r
t
t
i
i
e
e
s
s
I
I
n
n
f
f
o
o
This tutorial shows how to use @RequestBody to convert JSON from HTTP Request Body into Java Object (DTO).
Syntax
@RequestMapping("/AddPerson")
public String addPerson(@RequestBody PersonDTO personDTO) { ... }
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables @Controller, @RequestMapping, Tomcat Server
MyController
PersonDTO
Postman
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: bootspring_http_requestbody (add Spring Boot Starters from the table)
Create Package: DTO (inside main package)
Create Class: PersonDTO.java (inside package DTO)
Create Package: controllers (inside main package)
Create Class: MyController.java (inside package controllers)
PersonDTO.java
package com.ivoronline.bootspring_http_requestbody.DTO;
public class PersonDTO {
//PROPERTIES
//Used for Deserialization if there is no Constructor or Setters
//Jackson uses reflection to access private Properties.
public Long id;
public String name;
public Integer age;
}
MyController.java
package com.ivoronline.bootspring_http_requestbody.controllers;
import com.ivoronline.bootspring_http_requestbody.DTO.PersonDTO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/AddPerson")
public String addPerson(@RequestBody PersonDTO personDTO) {
//GET DATA FROM PersonDTO
String name = personDTO.name;
Integer age = personDTO.age;
//RETURN SOMETHING
return name + " is " + age + " years old";
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
Start Postman
POST
http://localhost:8080/addPerson
Headers (add Key-Value)
Content-Type: application/json
Body (option: raw)
{
"name" : "John",
"age" : 20
}
Postman
HTTP Response Body
John is 20 years old
Application Structure
pomx.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>