Java EE 7: Sending JSON Objects Over WebSockets 📎
Java EE 7 and particularly JSR 356: Java API for WebSockets supports Encoders to serialize any custom object into WebSocket stream. With JSR 353: Java API for JSON Processing the conversion between JsonObject
instances and streams is straightforward:
import java.io.IOException;
import java.io.Writer;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
public class JsonEncoder implements Encoder.TextStream<JsonObject> {
@Override
public void init(EndpointConfig config) {}
@Override
public void encode(JsonObject payload, Writer writer) throws EncodeException, IOException {
try (JsonWriter jsonWriter = Json.createWriter(writer)) {
jsonWriter.writeObject(payload);
}
}
@Override
public void destroy() {}
}
The Encoder
instance needs to be registered with the @ServerEndpoint annotation:
[...]
@ServerEndpoint(value = "/changes", encoders = {JsonEncoder.class})
public class ToDoChangeTracker {
private Session session;
@OnOpen
public void onOpen(Session session) {
this.session = session;
}
@OnClose
public void onClose() {
this.session = null;
}
public void onToDoChange([...]) throws EncodeException {
if (this.session != null && this.session.isOpen()) {
try {
JsonObject event = Json.createObjectBuilder().
add("name",[...]).
build();
this.session.getBasicRemote().sendObject(event);
} catch (IOException ex) {
//we ignore this
}
}
}
}
This example was taken from the 38th episode of the Effective Java EE Online Workshop. Sources are available from github.com/AdamBien/doit