代码之家  ›  专栏  ›  技术社区  ›  Andrew Eisenberg

JAX-RS响应为字符串生成转义JSON

  •  2
  • Andrew Eisenberg  · 技术社区  · 12 年前

    我正在使用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    }"
    

    这里发生的事情显然是字符串被转义了。相反,我想要原始字符串,但保持相同的内容类型。

    2 回复  |  直到 12 年前
        1
  •  2
  •   lefloh    12 年前

    如果您已经将JSON作为字符串,那么如果您使用此实体创建响应,则应该可以工作:

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response config() {
        return Response.ok(exportConfiguration()).build();
    }
    
        2
  •  0
  •   Andrew Eisenberg    12 年前

    为了回答我自己的问题,看起来我需要直接写响应对象。这样地:

    @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();
    }
    
    推荐文章