Spring @ResponseBody creates invalid JSON for primitive types

I have code from the REST API that uses @ResponseBody to return the result and MappingJacksonHttpMessageConverter to return it in JSON format.

All this works for complex objects. For primitives like int , boolean and string I get JSON that does not start with {or [. This is invalid JSON.

I was wondering how to correctly return just such a simple type? Should I encapsulate it in an object, for example { Result : true } ?

thanks

Code example:

 @RequestMapping( value = "/login", method = RequestMethod.POST) @ResponseBody public boolean Login(String username, String password) { return authenticationService.authenticate(username, password); } 

This will only return true or false , which is invalid JSON. It must be encapsulated in an object or array (if I understand correctly).

+7
json spring rest jackson
source share
2 answers

It returns true or false. And you are right that this is not json.

It cannot be json, because it is not an object, it is simply primitive, therefore its fine as is - it will be assigned to the javascript variable in your success handler.

If you return the list of Booleans, you will get an array:

 [true,false,true] 

If you must form json completely, do not return the primitive, use hashmap or a custom shell object.

 public @ResponseBody Map<String, Boolean> getTrue() { Map<String, Boolean> map = new HashMap<String, Boolean>(1){{put("result", Boolean.TRUE);}}; return map; } 

Returning a hash map is perhaps the easiest and best way to get the json you need:

 {"result":true} 
+8
source share

I found it convenient to use

 public class ObjWrapper<T> implements Serializable { private T obj; public ObjWrapper(T obj) { this.obj = obj; } public T getObj() { return obj; } } 

then in the controller:

 @RequestMapping("/getString") @ResponseBody public ObjWrapper<String> getString() { ... 

and on the client (jquery)

 $.getJson("getString", {}, function (data) { alert(data.obj); }) 

same with lists:

 public class ListWrapper<T> implements Serializable { private List<T> content; public ListWrapper(T... objects) { content = Arrays.asList(objects); } public ListWrapper(List<T> content) { this.content = content; } public List<T> getContent() { return content; } } 
+4
source share

All Articles