Issue
I have a controller endpoint that takes EmployeeRequest
as shown below:
{
"name": "Marry Boython",
"email": "[email protected]",
"country": "UK",
"age": "25"
}
For creating multiple employees, I use a static list in the Application class so that they are populated to the database when running the app. However, I want to create these employees from a json file and sending List<EmployeeRequest>
to the service.
I tried the following aproach, but not sure where I point the location of my json file. So, is that the right approach that I am looking to read json and send list of the items in it to the service?
@PostMapping(
value = "/createAll", consumes = "application/json", produces = "application/json")
public ResponseEntity<List<EmployeeDto>> createAll(
@RequestBody List<EmployeeRequest> requests) {
final List<EmployeeDto> employees = employeeService.create(requests);
return ResponseEntity.ok(employees);
}
Solution
Ok from my understanding you would need no body as request input. Instead, you'd want a controller that takes as input a file name so that you can dynamically load a .json file. Your controller method would look something like this:
private final ObjectMapper mapper;
private final ResourceLoader resourceLoader;
public Controller(ObjectMapper mapper, ResourceLoader resourceLoader) {
this.mapper = mapper;
this.resourceLoader = resourceLoader;
}
@PostMapping("/load/{fileName}")
public void loadResource(@PathParam("fileName") String fileName) throws IOException {
Resource resource =resourceLoader.getResource("classpath:"+fileName);
log.debug("Found file " + resource.getFile().getAbsolutePath());
List<Person> people = mapper.readValue(resource.getFile(), new TypeReference<>() {
});
log.info(String.valueOf(people));
}
Where the People.class
would be your list of objects that are contained in the json file (EmployeeRequest)
Your .json files would need to be placed with this structure:
Answered By - L_Cleo
Answer Checked By - Gilberto Lyons (JavaFixing Admin)