Issue
I have this code for a RestAPI (simplified for the purpose of this question).
public class UserRequestDTO {
private Long userId;
private List<Email> email;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public List<Email> getEmail() {
return email;
}
public void setEmail(List<Email> email) {
this.email = email;
}
}
@RestController
public class UserController {
@PostMapping(value = "/user", produces = "application/json")
public ResponseEntity<UserResponseDTO> addUser(@RequestBody UserRequestDTO userRequestDTO) {
....
}
}
The above code sucessfully creates userRequestDTO for the following POST request body (Postman) that has several emails:
{
"email": [
{
"type": "primary",
"value": "[email protected]"
},
{
"type": "primary",
"value": "[email protected]"
}
]
}
But it does not create userRequestDTO for this other POST request body that has just one email:
{
"email": {
"type": "primary",
"value": "[email protected]"
}
}
The thing is that I have a requirement to make both type of requests (one and several emails) work.
I cannot edit the json postman request. That's how it comes. I need the change to be in the Java code.
How to do that?
Thanks.
Solution
It is possible to configure deserialization in Jackson. For example:
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfiguration {
@Bean
@Primary
public ObjectMapper objectMapper() {
return new ObjectMapper().enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
}
}
Answered By - Alexander Kashpirovsky
Answer Checked By - Senaida (JavaFixing Volunteer)