Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @ResponseBody produces an invalid JSON for primitive types

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

like image 509
Oxmane Avatar asked Oct 16 '12 09:10

Oxmane


2 Answers

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 :

[true,false,true]

If you must have fully formed json don't return a primitive use a hashmap or custom wrapper object.

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

Returning a hashmap is probably the simplest and best way to get the json you require :

{"result":true}
like image 187
NimChimpsky Avatar answered Oct 14 '22 07:10

NimChimpsky


I've found 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 controller:

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

and on 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;
  }

}
like image 38
Vecnas Avatar answered Oct 14 '22 07:10

Vecnas