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.
@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 .
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);
}
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 ?)
Not possible. The variable name 'success' is lost. Use a map or create a little wrapper class.
public class BooleanResult {
public boolean success;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With