简体   繁体   中英

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,

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM