我正在尝试创建一个Java端点,它返回一个JSON数据数组,以供JQuery标记插件使用。
至少,FLOT的JSON数据需要是一个数字数组,即
[ [x1, y1], [x2, y2], ... ]假设我在Java中有一个Point对象列表,即
List<Point> data = new ArrayList<>();其中Point被定义为
public class Point {
private final Integer x;
private final Integer y;
public Point(Integer x, Integer y) {
this.x = x;
this.y = y;
}
...
}如果有的话,我需要在Jackson2对象上添加哪些方法或注释才能获得正确的JSON格式。目前,我正在以这种格式获得输出:
[{x:x1, y:y1}, {x:x2, y:y2} ...]当我需要这种格式时:
[[x1,y1], [x2,y2] ...]发布于 2014-04-28 16:15:00
您可以编写自定义Point序列化程序。
import java.io.IOException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
public class CustomPointSerializer extends JsonSerializer<Point> {
@Override
public void serialize(Point point, JsonGenerator gen, SerializerProvider provider) throws IOException, JsonProcessingException {
gen.writeStartArray();
gen.writeNumber(point.getX());
gen.writeNumber(point.getY());
gen.writeEndArray();
}
}然后,可以将自定义序列化程序类设置为Point类。
import org.codehaus.jackson.map.annotate.JsonSerialize;
@JsonSerialize(using = CustomPointSerializer.class)
public class Point {
private Integer x;
private Integer y;
public Point(Integer x, Integer y) {
this.x = x;
this.y = y;
}
public Integer getX() {
return x;
}
public void setX(Integer x) {
this.x = x;
}
public Integer getY() {
return y;
}
public void setY(Integer y) {
this.y = y;
}
}试试看
ObjectMapper mapper = new ObjectMapper();
List<Point> points = new ArrayList<Point>();
points.add(new Point(1,2));
points.add(new Point(2,3));
System.out.println(mapper.writeValueAsString(points));代码产生以下结果
[[1,2],[2,3]]希望这能有所帮助。
发布于 2014-04-28 15:49:56
您可以在一个特殊的getter方法上使用@JsonView注释,该方法返回一个intergers数组。下面是一个示例:
public class JacksonObjectAsArray {
static class Point {
private final Integer x;
private final Integer y;
public Point(Integer x, Integer y) {
this.x = x;
this.y = y;
}
@JsonValue
public int[] getXY() {
return new int[] {x, y};
}
}
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Point(12, 45)));
}
}输出:
[ 12, 45 ]https://stackoverflow.com/questions/23344099
复制相似问题