2
2
.
.
1
1
1
1
.
.
7
7
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
-
-
C
C
o
o
n
n
s
s
t
t
r
r
u
u
c
c
t
t
o
o
r
r
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows how to
use @RequestBody to convert JSON from HTTP Request Body into DTO
by calling DTO Constructor
Syntax
@RequestMapping("/AddPerson")
public String addPerson(@RequestBody PersonDTO personDTO) { ... }
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables @Controller and @RequestMapping. Includes 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: springboot_dto_json_object_constructor (add Spring Boot Starters from the table)
Create Package: controllers (inside main package)
Create Class: MyController.java (inside package controllers)
Create Package: DTO (inside main package)
Create Class: PersonDTO.java (inside package controllers)
PersonDTO.java
package com.ivoronline.springboot_dto_json_object_constructor.DTO;
public class PersonDTO {
//PROPERTIES
//Not used for Deserialization if there is Constructor or Setters
private String name;
private Integer age;
//SETTERS
//Not used for Deserialization if there is Constructor
public String getName() { return name; }
public Integer getAge () { return age; }
//CONSTRUCTOR
//Used for Deserialization
PersonDTO(String name, Integer age) {
this.name = name;
this.age = age;
}
}
MyController.java
package com.ivoronline.springboot_dto_json_object_constructor.controllers;
import com.ivoronline.springboot_dto_json_object_constructor.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.getName();
Integer age = personDTO.getAge();
//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/addAuthor
Headers (add Key-Value)
Content-Type: application/json
Body (option: raw)
{
"name" : "John",
"age" : 20
}
Postman
HTTP Response Body
John is 20 years old