I have a writeResponse method within a Spring controller which writes a DTO as Json :
private void writeResponse(String type , Object objectToWrite , ResourceResponse response){
try {
MyDTO myDto= new MyDTO ();
ObjectMapper mapper = new ObjectMapper();
response.getWriter().write(mapper.writeValueAsString(myDto));
}
catch (final JsonGenerationException e) {
log.error(e.getMessage());
} catch (final JsonMappingException e) {
log.error(e.getMessage());
} catch (final IOException e) {
log.error(e.getMessage());
}
}
The method writeResponse is called by multiple methods and each caller method is a different REST endpoint. Currently there is just one DTO type : MyDTO . However more DTO types will be added. To determine which DTO should be written there is a 'type' method parameter. So above method could become :
private void writeResponse(String type , Object objectToWrite , ResourceResponse response){
try {
if(type == "1"){
MyDTO myDto= new MyDTO ();
ObjectMapper mapper = new ObjectMapper();
response.getWriter().write(mapper.writeValueAsString(myDto));
}
else if(type == "2")
{
MyDTO2 myDto2= new MyDTO2 ();
ObjectMapper mapper = new ObjectMapper();
response.getWriter().write(mapper.writeValueAsString(myDto2));
}
}
catch (final JsonGenerationException e) {
log.error(e.getMessage());
} catch (final JsonMappingException e) {
log.error(e.getMessage());
} catch (final IOException e) {
log.error(e.getMessage());
}
}
This feels a little clunky. I'm trying to achieve a clean method returning a different JSON depending on which endpoint is called. Is there a better way than what I am suggesting ?
Note : above code is a mix of pseudocode and java.
ResourceResponse? Where does this method exist? In a service, controller, other?