Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use @ResponseBody to return a map<string, string>?

public class RestfulControllerImpl implements RestfulController {

  @Override
  @RequestMapping(value = "maptest", method = RequestMethod.GET)
  @ResponseBody
  public Object mapReturn() {
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("name", "test1");
    map.put("sex", "male");
    map.put("address", "1324");
    map.put("old", "123");
    return map;
  }  
}

I want to return a map<string, string> for the request, and it occurs

HTTP-406 not acceptable

How to implement the method to return a response body with a map and it shows in like a json object?

like image 214
Bingyu Yin Avatar asked Jul 06 '15 06:07

Bingyu Yin


1 Answers

If your Controller only return json (REST API) then annotate Class with @RestController instead of @Controller. Then you don't need to add @ResponseBody annotation to each and every Endpoint. Since we cleared the problem with missing @ResponseBody Below code will do what you want.

@GetMapping("/maptest")
public ResponseEntity<?> mapReturn() {
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("name", "test1");
    map.put("sex", "male");
    map.put("address", "1324");
    map.put("old", "123");
    return ResponseEntity.ok(map);
}

Here ResponseEntity is wrapper for Http response. Since I declared here as ResponseEntity<?> I can return any Object as json. (It is good when you have return error response as another object) But if you sure that it will only return Map Object you can write it as ResponseEntity<Map> (If you have separate error handler) Hope this is clear.

like image 54
Menuka Ishan Avatar answered Sep 17 '22 18:09

Menuka Ishan