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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With