Spring REST的JSON响应有反斜杠字符

时间:2017-03-21 01:28:20

标签: json spring rest

我的Spring REST服务编写如下:

@RequestMapping(value = "/{name}", method = RequestMethod.GET,
        consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> 
            getStudentByName(@PathVariable("name") String name)  {
    Map<String, Object> map = null;
    try {
        map = new HashMap<String, Object>();
        map.put("name", "Tom Joe);
        map.put("id", "t100");
        map.put("dept", "nuclear energy");          
    } catch (Exception e) {
        LOG.error("Error finding with name " + name, e);
    }

    return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
}

我在客户端得到这样的输出,基本上是一个字符串:

"{\"name\":\"Tom Joe\",\"id\":\"100\",\"dept\":\"nuclear energy\"}"

但我想要的输出是:

{
"name":"Tom Joe",
"id":"t100",
"dept":"nuclear energy"
}

有谁能告诉我如何避免发送反斜杠而是发送适当的json?我可以不回复地图吗?

1 个答案:

答案 0 :(得分:-2)

我在我的应用程序中尝试了您的代码,它似乎按预期工作:

@RestController
public class TestController {

...

@RequestMapping(value = "/{name}", method = RequestMethod.GET,
        consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getStudentByName(@PathVariable("name") String name) {
    Map<String, Object> map = null;
    try {
        map = new HashMap<String, Object>();
        map.put("name", "Tom Joe");
        map.put("id", "t100");
        map.put("dept", "nuclear energy");
    } catch (Exception e) {
        LOGGER.error("Error finding with name " + name, e);
    }

    return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
}
}

提供以下输出:

  

{“name”:“Tom Joe”,“id”:“t100”,“dept”:“核能”}

您使用的是哪个客户?我在chrome中使用Advanced Rest客户端。