I have a code from a REST API which uses @ResponseBody
to return the result, and a MappingJacksonHttpMessageConverter
to return it in a JSON format.
It all works well for complex objects.
For primitives like int
, boolean
and string
I get a JSON which does not start with { or [.
This is not a valid JSON.
I was wondering what is the proper way to return just a simple type like that?
Should I encapsulate it in an object such as { Result : true }
?
Thanks
Code sample:
@RequestMapping(
value = "/login",
method = RequestMethod.POST)
@ResponseBody
public boolean Login(String username, String password) {
return authenticationService.authenticate(username, password);
}
This will return just true
or false
which is an invalid JSON. It should either be encapsulated in an object or an array (if I understand correctly).
It does just return true, or false. And you are correct that is not json.
It can't be json because its not an object, it is simply a primitive, so its fine as is - it will be assigned to a javascript variable in your success handler.
If you return a list of Booleans you get an array :
If you must have fully formed json don't return a primitive use a hashmap or custom wrapper object.
Returning a hashmap is probably the simplest and best way to get the json you require :
I've found convenient to use
then in controller:
and on client (jquery)
same with lists: