Java Atmosphere Jersey从广播站点返回JSON对象

fivyi3re  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(95)

我尝试使用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);
    }
}

我知道我的数据绑定和POST JSON 'Notification'对象一样有效。
有没有什么方法可以使用JAXB JSON序列化将传递给'new Broadcastable()'的Object转换为JSON对象?

bmp9r5qi

bmp9r5qi1#

试试这个代码

@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());
            }
        }
    }
}

希望这对你有帮助...:)

相关问题