Issue
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
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
}
Answered By - Urosh T.
Answer Checked By - Candace Johnson (JavaFixing Volunteer)