在普通请求中强制JSON响应的方法如下:
@ResponseBody
注解来强制将返回值作为JSON响应。@RequestMapping(value = "/example", method = RequestMethod.GET)
@ResponseBody
public Map<String, Object> example() {
Map<String, Object> response = new HashMap<>();
response.put("key", "value");
return response;
}
@RestController
注解来替代@Controller
注解,这样所有的方法都将默认使用@ResponseBody
注解,强制将返回值作为JSON响应。@RestController
public class ExampleController {
@RequestMapping(value = "/example", method = RequestMethod.GET)
public Map<String, Object> example() {
Map<String, Object> response = new HashMap<>();
response.put("key", "value");
return response;
}
}
@JsonView
注解来强制将返回值作为JSON响应。public class ExampleView {
public interface DefaultView {
}
}
@RestController
public class ExampleController {
@RequestMapping(value = "/example", method = RequestMethod.GET)
public Map<String, Object> example() {
Map<String, Object> response = new HashMap<>();
response.put("key", "value");
return response;
}
}
@RequestMapping
注解的produces
属性来指定响应的内容类型为JSON。@RequestMapping(value = "/example", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String, Object> example() {
Map<String, Object> response = new HashMap<>();
response.put("key", "value");
return response;
}
以上方法可以强制将返回值作为JSON响应,并在普通请求中使用。
领取专属 10元无门槛券
手把手带您无忧上云