【问题标题】:Wildfly RestEASY return json from plain stringWildfly RestEASY 从纯字符串返回 json
【发布时间】:2015-02-19 15:10:26
【问题描述】:

我有一个角应用程序,我想为用户必须登录但应该能够从他离开页面的地方恢复的情况创建一个小型会话存储。

存储部分非常简单,因为我按原样存储接收到的 jsonstring。但是当我重新调整值时,字符串被转义为字符串而不是 json。有没有办法将字符串(已经是 json)作为 json 对象返回?

@Path("/session")
public class SessionStore extends Application {
    @POST
    @Path("/save/{variable}")
    @Consumes("application/json")
    public boolean save(@PathParam("variable") String var, String json) throws Exception {
        getSession().setAttribute(var, json);
        return true;
    }

    @GET
    @Path("/load/{variable}")
    @Produces("application/json")
    public Object load(@PathParam("variable") String var) {
        return getSession().getAttribute(var); // this string is already a json
    }
}

【问题讨论】:

    标签: json jakarta-ee resteasy


    【解决方案1】:

    如果您不希望您的返回值自动装箱为 json 格式,请告诉您的 JAX-RS 实现返回纯文本而不是使用 @Produces("text/plain") 的 json。

    @GET
    @Path("/load/{variable}")
    @Produces("text/plain")
    public String load(@PathParam("variable") String var) {
        //the cast may not be necessary, but this way your intention is clearer
        return (String) getSession().getAttribute(var);
    }
    

    【讨论】:

    • 这也会将Content-Type 标头更改为text/plain,这不是所需的行为。
    • @lefloh,我打算补充一下,但没有时间这样做,也没有测试我的替代解决方案。由于 OP 仅需要 Angular 的这些服务,因此暂时不会有问题。
    • 当您自己处理标题时,角度$http.get 确实没有问题。我在想人们使用一些带有 getJson 之类的函数的 JS-Lib 并想知道为什么会执行错误回调。
    【解决方案2】:

    我不知道您使用的是哪个 JSON 序列化程序。我无法用杰克逊重现这种行为。

    一开始我会把你方法的返回时间改成String。由于将字符串转换为 JSON 字符串没有意义,除非它已经是 JSON 字符串,因此您的 JSON 序列化程序不应触及它。如果它试图变得更智能,您可以为字符串注册一个自定义 MessageBodyWriter

    @Provider
    @Produces(MediaType.APPLICATION_JSON)
    public class JsonStringSerializer implements MessageBodyWriter<String> {
    
        @Override
        public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
            return type == String.class;
        }
    
        @Override
        public long getSize(String t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
            return -1;
        }
    
        @Override
        public void writeTo(String entity, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
            entityStream.write(entity.getBytes(Charset.forName("UTF-8")));      
        }
    
    }
    

    我强烈建议不要将@Produces 注释 更改为text/plain。这可能会导致返回正确的内容,但也会将Content-Type 标头更改为text/plain。因此,您正在发送 JSON,但告诉您的客户端它不是 JSON。如果客户相信你,他就不会再解析内容了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多