'Spring RequestBody with either List<Object> or Object. Name for both are same "data"
I want to handle json request for List of Object and Object it self in the same Spring controller. Below is the exact example.
Json Request for Single Object:
{"data":{"prop":"123456","prop2":"123456"}}
Json Request for List of Objects:
{"data":[{"prop":"123456","prop2":"123456"},{"prop":"123456","prop2":"123456"}]}
My Controller is as follow.
@PostMapping(path="/path")
public @ResponseBody String getSomething(@RequestBody Input data){
return service.getSomething(data);
}
I want to handle both of this requests in a single spring controller.
Appreciate your help. Thanks.
Solution 1:[1]
EDIT
You can create DTOs for your inputs but receive the @RequestBody
as a JSON string and then parse it as a list or a single object request.
DTO for a request list:
public class InputDataList {
private List<Input> data;
// getters and setters
}
DTO for a single request object:
public class InputDataSingle {
private Input data;
// getters and setters
}
Then on your controller:
@PostMapping(path="/path")
public @ResponseBody String getSomething(@RequestBody String json){
// this is better done in a service but for simplicity, I write it in the controller
try {
InputDataSingle data = new ObjectMapper().readValue(json, InputDataSingle.class);
// If fails to parse as a single object, parse as a list
} catch (Exception) (
InputDataList data = new ObjectMapper().readValue(json, InputDataList.class);
}
// handle objects in the service layer
}
Solution 2:[2]
Its been some time. However I was facing the same issue and was thinking whether any solution is there The below worked for me
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
private List<Data> data;
Solution 3:[3]
Sorry, Really not a good workaround (solution), because it is not kind of misleading and poor for maintainability, secondly not good at all to keep code in the catch block and this is violating the coding principles.
I would highly suggest splitting 2 endpoints one for single i.e (/something) and another for list (/something-batch)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | AbuSaad |