Reputation: 21
I am trying to create a rest controller which returns an object which contains a String, Long and a csv file. I am unable to do it because as soon I write the file creation logic in java, rather than returning it, it creates a file on my host.
I have already tried to write the entire object to the httpservletresponse using writer and output stream, but it did not give the expected result. I returned the object from controller, but instead of returning the object, it created a file on my host and did not return other values at all.
public class MyReturnObject {
private Long countOfRows;
private File csvDataFile;
private String errorMessage;
}
@RequestMapping(value = "/api/fetchInfo", method = RequestMethod.GET)
public MyReturnObject fetchInfoRestControllerMethod (String param1) {
//some logic/ service calls
return createMyReturnObject(values);
}
public MyReturnObject createMyReturnObject(List<CustomObject> values) {
File csvFile = new File("myinfo.csv");
file.createNewFile();
FileWriter writer = new FileWriter(csvFile);
writer.write("test");
//some lines
MyReturnObject returnObject = MyReturnObject.builder()
.countOfRows(x)
.csvDataFile(csvFile)
.errorMessage(y).build();
return returnObject;
}
This is just some dummy code I wrote. The object that I am building in createMyReturnObject
is not returning the expected result. I am thinking if it is possible to return something like object MyReturnObject
from a rest controller. Please help me with ideas to get expected results.
Upvotes: 2
Views: 1729
Reputation:
Serialize your class MyReturnObject use a jackson library or gson in you project.
@RequestMapping(value = "/api/fetchInfo", method = RequestMethod.GET)
public @ResponseBody MyReturnObject fetchInfoRestControllerMethod (String param1) {
return MyReturnObject.builder()
.countOfRows(x)
.csvDataFile(csvFile)
.errorMessage(y).build();
}
Upvotes: 0
Reputation: 2571
Unfortunately, you cannot have two response bodies at the same time. You can have it either set to text/csv
or to text/json
and you can return a single response body at a time.
However, you can convert your CSV into bytes and Base64.enocode
it and put inside of the object. You can also store your CSV in a string and return it with a custom line separator.
Upvotes: 1