如何将文字JSON字符串作为JSON对象返回

时间:2018-08-07 21:11:52

标签: java json spring jackson

我刚刚开始我的第一个开发工作,并且该公司正在使用Spring框架。构建当前REST服务的人员已退休,因此我在这里寻求帮助。这是他们当前使用的方式:

@RequestMapping(value = "/hello", method = RequestMethod.GET)
public ResponseEntity<?> hello() {
    ModelMap map = new ModelMap();
    map.put("Hello", "World");
    return new ResponseEntity<ModelMap>(map, HttpStatus.OK);
}

返回{"Hello":"World"}

我需要添加一个新方法,该方法的JSON已经作为Java字符串生成,但是它仅返回带引号的字符串,而不是JSON对象。我的新方法:

@RequestMapping(value = "/test", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> getMessage() {

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_JSON);

    String response = "{\"message\":\"The message value.\"}";
    return new ResponseEntity<String>(response, responseHeaders, HttpStatus.OK);
 }

这将返回"{\"message\":\"The message value.\"}"

这是一个带有外部引号的字符串,所有内部引号都转义了,而不是像第一个方法那样使用纯JSON。我该如何阻止它返回一个字符串并返回一个不带引号和转义的JSON对象?

0 个答案:

没有答案