automation-1 automation-2 automation-3 automation-4 consultancy-1 consultancy-2 consultancy-3 consultancy-4 facebook google-plus outsourcing-1 outsourcing-2 outsourcing-3 outsourcing-4 power-engineering-1 power-engineering-2 power-engineering-3 power-engineering-4 twitter

Genson JSON format for byte arrays

Genson is a small and flexibile library for Java to JSON and vice versa conversion. Main advantages of this library are speed, size and easy of use.

It is very easy to configure Jersey to work with genson – all that is needed is to place genson in the classpath. Jersey will detect it automatically and use for Java <-> JSON conversion.

JSON format differences between genson and RestyGWT

We have used genson with Jersey on the server side, while the client side is GWT application using RestyGWT for REST calls. This solution works well for us, with one exception – binary arrays are treated differently by genson and RestyGWT.

When Jersey serializes a class below using genson default configuration,

public class TestClass {
    int id;
    byte[] content;

    TestClass(int id, byte[] content) { = id;
        this.content = content;

field content will be serialized using base64 encoding. This is default approach used by genson, however, this might not be adequate for other parsers. Example output and code that generates it is shown below:

public class TestJSON {
    public static void main(String[] args) {
        Genson genson = new Genson();
        String json = null;

        try {
            json = genson.serialize(new TestClass(5, "ABCD".getBytes()));
        } catch (Exception e) {


Field content is encoded in base64 as shown below:


RestyGWT uses Jackson compatible JSON parsing and expects byte arrays to be serialized as array of numbers. Using above example, JSON expected by RestyGWT would be as following:

{"content":[65, 66, 67, 68],"i":5}

Changing genson default format for byte arrays

It was not possible to make Jackson compatible JSON output from genson without custom serializers prior to version 0.99. In the version 0.99 new option useByteAsInt is added, which supports serialization of byte arrays as array of numbers.

Activation of this options requires adding one class to the classpath, as shown below:

public class GensonProvider implements ContextResolver {
    private final Genson genson = new Genson.Builder().useByteAsInt(true).create();

    public Genson getContext(Class type) {
        return genson;

This class will be automatically found and used by Jersey.

Share this article additional message.