2
2
.
.
1
1
1
1
.
.
4
4
F
F
r
r
o
o
m
m
R
R
e
e
q
q
u
u
e
e
s
s
t
t
P
P
a
a
r
r
a
a
m
m
e
e
t
t
e
e
r
r
s
s
-
-
U
U
s
s
i
i
n
n
g
g
M
M
a
a
p
p
-
-
C
C
u
u
s
s
t
t
o
o
m
m
i
i
z
z
e
e
S
S
e
e
t
t
t
t
e
e
r
r
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows how to
Deserialize HTTP Request Parameters into Map<String, Object> (how to automatically load them into Map)
use ObjectMapper to load that Map into PersonDTO
use setters() to customize values that go into PersonDTO Properties (converting "1,67" into "1.67")
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: Controller Annotations, Tomcat Server
PersonDTO
http://localhost:8080/AddPerson
Tomcat
Browser
MyController
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_deserialize_requestparameters_objectmapper (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.springboot_deserialize_requestparameters_objectmapper.DTO;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true) //To avoid Error if Request contains additional Parameters
public class PersonDTO {
//PROPERTIES
public String name;
public Float height;
//CONVERSION SETTER
@JsonProperty("height") //Map Request Parameter to Setter
public void setHeight(String heightString) {
heightString = heightString.replace(',', '.');
this.height = Float.parseFloat(heightString);
}
}
MyController.java
package com.ivoronline.springboot_deserialize_requestparameters_objectmapper.controllers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ivoronline.springboot_deserialize_requestparameters_objectmapper.DTO.PersonDTO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/AddPerson")
public String addPerson(@RequestParam Map<String, Object> requestParameters) {
PersonDTO personDTO = new ObjectMapper().convertValue(requestParameters, PersonDTO.class);
return personDTO.name + " is " + personDTO.height + " meters high";
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
http://localhost:8080/AddPerson?name=John&height=1,67
Application Structure
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>