I have the following method, whenever the xml paramater is present in the query string I want to return xml otherwise json.
@RequestMapping(value="/flight/{number}")
public ResponseEntity getFlight(@PathVariable("number") String number,
@RequestParam(value="xml",required = false) String xml) {
try {
if(flightservice.getFlight(number) != null) {
if(xml != null) {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_XML);
return new ResponseEntity(buildFlightResponse(flightservice.getFlight(number)), responseHeaders, HttpStatus.OK);
} else {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity(buildFlightResponse(flightservice.getFlight(number)), HttpStatus.OK);
}
} else {
return new ResponseEntity(getErrorResponse("404", "Flight with number "+number+" not found"), HttpStatus.NOT_FOUND);
}
} catch(Exception ex) {
return new ResponseEntity(getErrorResponse("400", ex.getMessage()), HttpStatus.BAD_REQUEST);
}
}
I have set the defaultContentType to MediaType.APPLICATION_JSON in my spring boot config class. Problem is for the xml part, even when I set the responseHeaders contentType to APPLICATION_XML I get json response which is not formatted correctly.
Is there any way I can return xml or json based using if .. else conditions.