Search code examples
javajersey-2.0server-sent-events

Sending POJOs in SSE event with Jersey?


I would like to be able to send a POJO via SSE with Jersey. For example, this (using the older Jersey API) works:

final OutboundEvent.Builder eventBuilder = new OutboundEvent.Builder();
eventBuilder.name("message-to-client");
eventBuilder.data(String.class, "Hello world " + i + "!");
final OutboundEvent event = eventBuilder.build();
eventOutput.write(event);

while this does not:

final OutboundEvent.Builder eventBuilder = new OutboundEvent.Builder();
eventBuilder.name("message-to-client");
eventBuilder.data(Item.class, new Item());
final OutboundEvent event = eventBuilder.build();
eventOutput.write(event);

An endpoint that returns "new Item()" gets me the JSON I would expect, but it blows up if I try that via SSE. Is what I'm wanting to do just not possible, or am I missing something fundamental?


Solution

  • You need to set the media type so Jersey knows to find the right provider to serialize it. It will default to text/plain if you don't set it. So currently, Jersey is looking for a provider to handle text/plain-POJO, which it can't find.

    eventBuilder.mediaType(MediaType.APPLICATION_JSON);