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