[英]JAX-RS response producing escaped JSON for a string
我正在使用JAX-RS来生成Web服务。 对于此Web服务,我有一个需要发送给用户的JSON字符串,但是问题是JAX-RS在发送该字符串之前对其进行了转义。 这是具体的问题。
该服务如下所示:
@GET
@Produces("application/json")
public String serializeConfiguration() {
return exportConfiguration();
}
用户转到http://mycompany.com/export-configuration
用户希望得到以下回应:
{
"myconfig" : "some stuff"
}
但是却得到:
"{\n \"myconfig\" : \"some stuff\"\n }"
这里发生的事情显然是字符串已被转义。 相反,我需要原始字符串,但要保持相同的内容类型。
如果您已经拥有JSON作为String,那么在使用此实体创建Response时应该可以使用:
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response config() {
return Response.ok(exportConfiguration()).build();
}
要回答我自己的问题,看起来我需要直接写到响应对象。 像这样:
@GET
public void serializeConfiguration(@Context HttpServletResponse response) throws IOException {
response.setContentType(MediaType.APPLICATION_JSON);
response.setStatus(200);
response.setCharacterEncoding(Charsets.UTF_8.name());
response.getWriter().write(exportConfiguration());
response.getWriter().close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.