0

I have a Spring 3 controller that returns a JSON object. I am using @ResponseBody annotation, and jackson-mapper-asl jar, with which the Spring will handle the JSON conversion automatically. The 3 return statements returns different JSON format. Can this be handled by modifying the return type of getPersonDetails method with Object or is there a better way.

@RequestMapping(value="/test", method=RequestMethod.GET)
public @ResponseBody List<Person> getPersonDetails() {


    List<Person> listPerson = null;
    try {
        // Call to service and get the list of Person
        listPerson = getPersonList();
        if(CollectionUtils.isNotEmpty(listPerson)) {
            // Return JSON object
            //{"Name":"XYZ", "Age":25}
        } else {
            // Return JSON object
            //{"InformationMessage":"No data found."}
        }
    } catch(final Exception e) {
        // Return JSON object
        // {"ExceptionMessage":"Exception in controller."}
    }
}
Shrihastha
  • 71
  • 1
  • 5
  • 16

5 Answers5

1

You could to something like this

@RequestMapping(value="/test", method=RequestMethod.GET)
public @ResponseBody ResponseEntity<List<Person>> getPersonDetails() {
try{
if(dataAvailable) // if success 
{ 

return new ResponseEntity<List<Person>>(yourlist, responseHeaders, HttpStatus.OK);
}
else{
return new ResponseEntity<List<Person>>(HttpStatus.NOT_FOUND);
}

}catch(Exception e){
// your custom exception here
throw new PersonNotFoundException();
}

}

Note : Have typed here not in IDE, any syntactical mistakes feel free to edit.

Pragnani
  • 20,075
  • 6
  • 49
  • 74
1

I would use ResponseEntity<?>

@RequestMapping(value="/test", method=RequestMethod.GET)
public @ResponseBody ResponseEntity<List<Person>> getPersonDetails() {


    List<Person> listPerson = null;
    try {
        // Call to service and get the list of Person
        listPerson = getPersonList();
        if(CollectionUtils.isNotEmpty(listPerson)) {
            return new ResponseEntity<>(listPerson, HttpStatus.OK);
        } else {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
    } catch(final Exception e) {
         return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Evgeni Dimitrov
  • 21,976
  • 33
  • 120
  • 145
0

Besides: there is no need to indicate via a "message object", that something was wrong. That's what HTTP-Status-Codes are for.

I would go for injecting a HttpServletResponse and use the setStatus() to indicate an Error, indicating a 404 or a 500. Additionally, you could a Message to the body with getWriter().write("{\"ExceptionMessage\":\"Exception in controller.\"}")

@RequestMapping(value="/test", method=RequestMethod.GET)
public @ResponseBody List<Person> getPersonDetails(HttpServletResponse response) {
    List<Person> listPerson = null;
    try {
        listPerson = getPersonList();
        if(!CollectionUtils.isEmpty(listPerson)) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("Whatever you want");
        }
    } catch(final Exception e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write("Whatever you want");
    }
    return listPerson;
}
Thomas Junk
  • 5,588
  • 2
  • 30
  • 43
0

Throw specific exceptions from the controller method. For example in your case , a custom PersonNotFoundException if list is empty and ServiceException for unknown errors . And handle these exceptions via @ExceptionHandlers with a return type of ResponseEntity.

Controller method should have return type as List only.

This will help you to have a neat documentation as well.

Try searching how to use ExceptionHandlers in spring.

Hope this answers your question.

PyThon
  • 1,007
  • 9
  • 22
0

you can create JResponse class and save your data into.

public class JSonResponse{
  private Object result;
  private String statu;

  // 
}


 @RequestMapping(value="/test", method=RequestMethod.GET)
 public @ResponseBody JSonResponse getPersonDetails() {
  JSonResponseres = new JSonResponse();
  List<Person> listPerson  = null;
  try {
    // Call to service and get the list of Person
    listPerson = getPersonList();
    if(CollectionUtils.isNotEmpty(listPerson)) {
        res.setResult(listPerson);
        res.status("SUCCESS");
     } else {
        res.setResult("Not Found Data");
        res.status("FAIL");
     }
  } catch(final Exception e) {
    // Return JSON object
    // {"ExceptionMessage":"Exception in controller."}
 }

  return res;
}
Hadi J
  • 16,989
  • 4
  • 36
  • 62