8

I'm writing a spring rest method to get details from database and set it in a response POJO and then return it. Currently I need to produce this response in CSV instead of default json when the URL is hit using POSTMAN or RC like a downloadable CSV file with data. I googled many sites but am not sure of few logics.

  1. Do we need to write business logic to convert pojo class values to csv format or does spring has any conversion mechanism ?
  2. Produces = "text/csv" is being mentioned on many places, does this convert response properly ?

Currently I haven't written any code for CSV conversion.

@GetMapping("/batch/export" , produces="text/csv")
public ResponseEntity<ApplicationResponse> getBatchDetails(
        HttpServletRequest request) {

    ApplicationRequest appRequest = ApplicationServiceMapper.mapRequestFromHttpRequest(request);
    ApplicationResponse response = appService.getDBDetails(appRequest);
    return new ResponseEntity<>(response, HttpStatus.OK);

}

Here response is the one that service returns with all the data in its pojo format and if we do not give produces in annotation then by default spring will return response json. Can someone guide me? Thanks in advance.

2

1 Answer 1

6

Just using the @GetMapping with produces="text/csv" is not enough. It is only responsible for setting the response header Content-Type: text/csv.

You'll need to add the response as a parameter HttpServletResponse response, convert your POJO into a valid csv file, and only then, write the csv file into the HttpServletResponse.

Sign up to request clarification or add additional context in comments.

1 Comment

This kinda answered my question, but what exactly I did was to use OpenCSV api completed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.