Spring中返回JSON数据

问题

这里驾驶不能使用注解@ResponseBody,想要在响应头中设置返回json返回。html

解决

添加xml配置java

<mvc:annotation-driven />

添加HttpHeaders设置web

@RequestMapping(value = "/json", method = RequestMethod.GET)
public ResponseEntity<String> bar() {
    final HttpHeaders httpHeaders= new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>("{\"test\": \"jsonResponseExample\"}", httpHeaders, HttpStatus.OK);
}

**注意:**这里没有使用注解@ResponseBody。 还应该了解以下代码不会生效:spring

// 无效设置
@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> bar() {
    final HttpHeaders httpHeaders= new HttpHeaders();
    return new ResponseEntity<String>("{\"test\": \"jsonResponseExample\"}", httpHeaders, HttpStatus.OK);
}

这里只是对请求的约束,并非会响应的约束,参考文档RequestMapping#produces()json

参考: Spring MVC 4: “application/json” Content Type is not being set correctlyapi

相关文章
相关标签/搜索