Neeraj
Neeraj

Reputation: 58

How to return xml or json in spring boot using ResponseEntity

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.

Upvotes: 0

Views: 5817

Answers (1)

Praneeth Ramesh
Praneeth Ramesh

Reputation: 3564

You may need to return a Jaxb object inside your ResponseEntity. When Jaxb is present in the classpath springs configures a Jaxb HttpMessageConverter.

And hence when you return a Jaxb object like

@XmlRootElement
public class MyResponse {

}

Spring converts this to xml and writes as response. Write two Class as your response, one as Jaxb and one as jackson to and build build and return the ResponseEntity accordingly.

Upvotes: 1

Related Questions