Java Reference
In-Depth Information
Transforming POJOs to JSON
In our current example, we transformed our Seat object to JSON manually. Normally, we
don't want to do it this way; there are many libraries that will do the transformation for us.
One of them is GSON from Google. Additionally, we can register an encoder/de-
coder class for a WebSocket endpoint that will do the transformation automatically. Let's
look at how we can refactor our current solution to use an encoder.
First of all, we must add GSON to our classpath. The required Maven dependency is as fol-
Next, we need to provide an implementation of the
javax.websocket.Encoder.Text interface. There are also versions of the
javax.websocket.Encoder.Text interface for binary and streamed data (for both
binary and text formats). A corresponding hierarchy of interfaces is also available for de-
coders ( javax.websocket.Decoder ). Our implementation is rather simple. This is
shown in the following code snippet:
public class JSONEncoder implements Encoder.Text<Object> {
private Gson gson;
public void init(EndpointConfig config) {
gson = new Gson(); [1]
public void destroy() {
// do nothing
Search WWH ::

Custom Search