Java Atmosphere Jersey 从 Broadcastable 返回 JSON 对象

标签 java json websocket jersey atmosphere

我正在尝试使用 Atmosphere 返回 JAXB 注释的 POJO 的 JSON 表示。

@Path("/entity/{topic}")
public class JerseyPubSub
{
    @PathParam("topic")
    private Broadcaster topic;

    @GET
    @Produces("application/json")
    public SuspendResponse<String> subscribe()
    {
        return new SuspendResponse.SuspendResponseBuilder<String>()
            .broadcaster(topic)
            .outputComments(true)
            .build();
    }

    @POST
    @Broadcast
    @Produces("application/json")
    public Broadcastable publish(Notification notification)
    {
        return new Broadcastable(notification, topic);
    }
}

我知道我的数据绑定(bind)工作正常,因为 POSTing JSON“通知”对象工作正常。

我是否可以使用 JAXB JSON 序列化将传递到“new Broadcastable()”的对象转换为 JSON 对象?

最佳答案

试试这段代码

@AtmosphereService(broadcaster=JerseyBroadcaster.class)
@Path("entity/{topic}")
public class WebService {
@PathParam(value="topic")
String topic;
@Context
private BroadcasterFactory factory;


    @Suspend(contentType = "application/json", listeners = {OnDisconnect.class})
    @GET
    public Broadcastable suspend() {
        return new Broadcastable( factory.lookup(topic, true ) );       
    }


    @Broadcast(writeEntity = false)
    @POST
    @Produces("application/json")
    public Response publish(Notification notification) {
        return new Response(notification);
    }


    public static final class OnDisconnect extends AtmosphereResourceEventListenerAdapter {
    private final Logger logger = LoggerFactory.getLogger(WebService.class);


    @Override
        public void onDisconnect(AtmosphereResourceEvent event) {
            if (event.isCancelled()) {
               logger.info("Browser {} unexpectedly disconnected", event.getResource().uuid());
            } else if (event.isClosedByClient()) {
               logger.info("Browser {} closed the connection", event.getResource().uuid());
            }
        }
    }
}

希望这会有所帮助...:)

关于Java Atmosphere Jersey 从 Broadcastable 返回 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21409865/

相关文章:

java - 使用 Criteria 进行连接

mysql - 日期格式发生奇怪的变化

python - GET curl 调用不返回 JSON 对象

javascript - 遍历 PHP 中的对象数组

c - Websockets、碎片和通过 recv 提供的可用数据

java - PowerMockRule 与 EasyMock 一起 NOT Moquito

java - JPA 无法反序列化 Java 8 LocalDateTime

java - 在 Java 中使用 GSON 验证 JSON

javascript - AngularJS:在指令模板函数中返回一个 promise

spring-boot - CometD 应用程序是否需要强制使用 Websocket 协议(protocol)