我有这样的代码:
@RestController
@RequestMapping("api/v1/student")
public class StudentController {
@GetMapping
public ResponseEntity<String> serviceOk() {
return new ResponseEntity<>("service OK", HttpStatus.OK);
}
它又回到了我身边
service OK
而不是
"service OK"
确实,“service OK”是有效的 JSON 格式,但 service OK 不是。 那么我如何转换我的 web 服务,以便强制以 json 进行序列化,即使是简单的字符串格式?
您可以使用gson。以下代码应该可以工作:
// import com.google.gson.Gson; Importing gson library!
private static final Gson gson = new Gson();
@GetMapping
public ResponseEntity<String> serviceOk() {
return new ResponseEntity<>(gson.toJson("service OK"), HttpStatus.OK);
}
您是否尝试像这样将
produces
添加到 @GetMapping 中?
@GetMapping(value="", produces = MediaType.TEXT_PLAIN_VALUE)
public String serviceOk() {
return "service OK";
}
否则如果你想使用ResponseEntity:
@GetMapping()
public ResponseEntity<String> serviceOk() {
var httpHeaders = new HttpHeaders();
httpHeaders.setContentType(new MediaType("text", "plain", StandardCharsets.UTF_8));
return new ResponseEntity<>("Text Message here", httpHeaders, HttpStatus.OK);
}