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 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> {

    public void init(EndpointConfig config) {}

    public void encode(JsonObject payload, Writer writer) throws EncodeException, IOException {
        try (JsonWriter jsonWriter = Json.createWriter(writer)) {

    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;

    public void onOpen(Session session) {
        this.session = session;

    public void onClose() {
        this.session = null;

    public void onToDoChange([...]) throws EncodeException {
        if (this.session != null && this.session.isOpen()) {
            try {

                JsonObject event = Json.createObjectBuilder().

            } 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


Helpful, tx!
Why new writer is created from parameter?
If use only parameter writer, do I need to close parameter writer?

Posted by david on March 22, 2016 at 01:18 PM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments