Maxim R
Maxim R

Reputation: 199

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.

Upvotes: 18

Views: 24097

Answers (4)

Burak Keceli
Burak Keceli

Reputation: 953

I am using jsonobject to do this.

return new JSONObject().put("result",true).toString().

Upvotes: 0

Oliver
Oliver

Reputation: 1380

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 ?)

Upvotes: 3

Bohuslav Burghardt
Bohuslav Burghardt

Reputation: 34776

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);
}

Upvotes: 32

atamanroman
atamanroman

Reputation: 11808

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

public class BooleanResult {
    public boolean success;
}

Upvotes: 1

Related Questions