Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in Spring MVC 4 return Boolean as JSON?

I have a simple method in Controller

@RequestMapping("admin")
public @ResponseBody
Boolean admin() {
    Boolean success = true;
    return success;
}

and in respond i want return { "success": true }

Annontation @ResponseBody says that the response will be JSON. But now in repsonse I recieve just true.

Is there is any other way how to solve it?

Or I should to do something like

@RequestMapping("admin")
public @ResponseBody
Map<String, Boolean> admin() {
    Map<String, Boolean> success = new TreeMap<String, Boolean>();
    success.put("success", true);
    return success;
}

I would like to know best practise for this.

like image 727
Maxim R Avatar asked Oct 17 '15 09:10

Maxim R


People also ask

Does rest controller return view?

@RestController is not meant to be used to return views to be resolved. It is supposed to return data which will be written to the body of the response, hence the inclusion of @ResponseBody .


3 Answers

You can't return a primitive type (or a primitive wrapper type) and get JSON object as a response. You must return some object, for instance a Map or custom domain object.

The Map approach shown in your question is perfectly valid. If you want you can compact it into a nice one-liner by using Collections.singletonMap().

@RequestMapping
@ResponseBody
public Map<String, Boolean> admin() {
    return Collections.singletonMap("success", true);
}
like image 134
Bohuslav Burghardt Avatar answered Oct 14 '22 05:10

Bohuslav Burghardt


You can't return a boolean, however, consider using ResponseEntities and use the HTTP status code to communicate success.

public ResponseEntity<String> admin() {
    if (isAdmin()) {
        return new ResponseEntity<String>(HttpStatus.OK);
    } else {
        return new ResponseEntity<String>(HttpStatus.FORBIDDEN);            
    }
}

This method will return an empty document, but you can control the status code (FORBIDDEN is only an example, you can then chose the status code that is more appropriate, e.g. NOT FOUND ?)

like image 30
Oliver Avatar answered Oct 14 '22 07:10

Oliver


Not possible. The variable name 'success' is lost. Use a map or create a little wrapper class.

public class BooleanResult {
    public boolean success;
}
like image 43
atamanroman Avatar answered Oct 14 '22 07:10

atamanroman