Spring @ResponseBody produces an invalid JSON for

2019-04-26 17:24发布

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

2条回答
Viruses.
2楼-- · 2019-04-26 18:14

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}
查看更多
Juvenile、少年°
3楼-- · 2019-04-26 18:14

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

}
查看更多
登录 后发表回答