【问题标题】:Using Atmosphere to return JSONP serialized objects使用 Atmosphere 返回 JSONP 序列化对象
【发布时间】:2012-02-14 23:52:49
【问题描述】:

我想在我的一个项目中使用 Atmosphere,但在将简单的 POJO-s 序列化为 JSONP 时遇到了一些问题。我不明白@Produces 注释和我之前成功使用的必要com.sun.jersey.api.json.JSONWithPadding 对象之间的关系,以便在简单的RESTful 服务中序列化我的POJO-s。

这是我的挂起方法:

@GET
  @Path("/notification")
  @Produces( { "application/x-javascript", MediaType.APPLICATION_JSON })
  @Suspend
  public JSONWithPadding getNextNotification(
    @QueryParam("callback") @DefaultValue("callback") String callback) {
    Random random = new Random();
    Notification n = new Notification();
    n.setMessage("Message is " + Long.toHexString(random.nextLong()));
    n.setMessage("S-" + Long.toHexString(random.nextLong()));
    return new JSONWithPadding(n, callback);
  }

这会按预期向我返回适当的 JSON 字符串。问题来了。我有返回的广播方法:

@Broadcast({XSSHtmlFilter.class, JsonpFilter.class})
  @GET
  @Path("/broadcast2")
  public Notification broadcast2() {
    Random random = new Random();
    Notification n = new Notification();
    n.setMessage("Message is " + Long.toHexString(random.nextLong()));
    n.setMessage("S-" + Long.toHexString(random.nextLong()));
    return n;
  }

这会产生以下异常:

Caused by: com.sun.jersey.api.MessageException: A message body writer for Java class com.ericsson.nss.entities.Notificaion, and Java type class com.ericsson.nss.entities.Notification, and MIME media type application/octet-stream was not fund

框架似乎想要序列化 ​​Notification 对象但无法这样做。 JsonpFilter 似乎空闲。我不确定此方法是否应该返回 Notification 或 JSONWithPadding 包装对象。如果我从 @Broadcast 注释中删除过滤器,则暂停方法会发出“com.ericsson.nss.entities.Notification@308be6”字符串。这比异常更好,但仍然不是 JSONP 消息。不幸的是,从 maven repo 构建的最新 rest-chat 演示无法运行(其他人提到的 /chat 上的 404)。

如果我的广播方法返回 JSONWithPadding 实例并且过滤器已关闭,则广播请求会获得有效的 JSONP 响应,但暂停的线程会再次返回 com.ericsson.nss.entities.Notification@7f84c9。

您能告诉我如何正确使用过滤器和注释吗?

(我用的是最新的0.9版Atmosphere)

【问题讨论】:

    标签: java jersey comet atmosphere


    【解决方案1】:

    我只能通过从我的方法返回 String 实例并使用 Jackson 手动处理 JSONP 序列化来使其工作。

    【讨论】:

      猜你喜欢
      • 2012-02-14
      • 2018-02-13
      • 2019-06-13
      • 2016-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2021-10-13
      相关资源
      最近更新 更多