Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC returning JSONS and exception Handling

I am using Spring MVC with Controllers, my question is how do I return a JSON response which is different from the @ResponseBody object which is returned and convereted to a JSON to be returned.

To elaborate further, I have the object called "UserDetails" which has two fields called "name", "emailAddress"

@ResponseBody UserDetails

now the json returned will look like

{ name : "TheUsersName", emailAddress:"[email protected]" }

Is there any way I can modify the json before returning (ALL jsons in all methods across all controllers) where a "status" field will be added and the other json data will be under the "data" key in the json.

Also how do I return a json to the frontend when the java server from somewhere throws an exception, the json should have "status : false" and the exception name (atleast the status part though)

like image 925
MilindaD Avatar asked Mar 22 '11 17:03

MilindaD


2 Answers

Create a response class:

public class Response<T> {
    T data;
    boolean status = true;

    public Response(T d) { data = d; }
}

Then return that from your controllers:

@ResponseBody public Response getUserDetails) {
    //...
    return new Response(userDetails);
}

For the exception you'll want to return an object like:

public class BadStatus {
    String errorMessage;
    boolean status = false;

    public BadStatus(String msg) { errorMessage = msg; }
}

@ExceptionHandler(Exception.class)
public BadStatus handleException(Exception ex, HttpServletRequest request) {
  return new BadStatus(ex.getMessage());
}
like image 99
sourcedelica Avatar answered Nov 04 '22 23:11

sourcedelica


Yes. Return a model and a view instead.

public ModelMap getUserDetails() {
    UserDetails userDetails; // get this object from somewhere
    ModelMap map = new ModelMap()(;
    map.addAttribute("data", userDetails);
    map.addAttribute("success", true);
    return map;
}

To add the exception you'd do it the same way with a key and success = false.

like image 29
Robby Pond Avatar answered Nov 04 '22 22:11

Robby Pond