2017-03-21 81 views
0

我写这样我的春节,REST服务:JSON响应具有反斜杠字符

@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?我能否做到这一点返回地图?

+0

我会尝试生产= MediaType.APPLICATION_JSON,而MIME类型APPLICATION_JSON_VALUE给你一个字符串转换。 – Tim

+0

@Tim那不会编译。 MediaType.APPLICATION_JSON是一个MediaType值。 'produce'期望'String []'。 –

+0

不知道为什么我的下面的答案是downvoted,但代码似乎工作正常..我会检查您使用的客户端,如果它是一个Java客户端它可能会将转义字符添加到响应时显示它。 – Pete

回答

-1

我想你的代码在我的应用程序,它似乎可以按预期工作:

@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); 
} 
} 

提供了以下的输出:

{ “名”: “汤姆·乔”,“ID “:”t100“,”dept“:”nuclear energy“}

您正在使用哪个客户端?我在Chrome中使用Advanced Rest客户端。

+0

令人惊讶。我正在使用我自己的Java客户端进行测试。基本上,创建HttpURLConnection并使用其输入流获取响应。我得到的回应,但它是一个单一的字符串,而不是良好的JSON。 – sburnwal

+0

你在浏览器中试过了吗? – Pete

+0

你是对的。 Service确实返回正确的json,但Gson.toJson(响应)正在添加这些反斜杠。对不起,这篇文章! – sburnwal