Search code examples
javajsonjacksonjackson-modules

Jackson Json serialization


I'm using Jackson 2.4 and I need to generate data to be process by d3.js.

d3.js want my json values to be format like this :

values : [[0, 13.5],[1, 2.5],[2, 5],[3, 41.2]]

In my Java model I have :

public class Series {

    private String key;
    private List<Entry> values;

    ...

    public void addEntry(int x, double y) {
        values.add(new Entry(x, y));
    }

    public class Entry {
        private int x;
        private double y;

        ...        
    }
}

It is only for serialization, not for deserialization, so is there a way with Jackson annotation to have the json generate as I want because for now it generates this :

values : [{x: 0, y: 13.5},{x: 1, y: 2.5},{x: 2, y: 2, 5},{x: 3, y: 41.2}]

Thanks,


Solution

  • The simplest way is to use @JsonValue. Try adding this to your Entry class:

    @JsonValue
    public Object[] jsonArray() {
        return new Object[]{Integer.valueOf(x), Double.valueOf(y)};
    }
    

    (You could also return a double[], since this is just going to get converted to a JavaScript number, or use autoboxing, but this is a bit clearer IMO.)