我正在尝试创建一个Java REST端点,该端点返回一个JSON数据数组,供JQuery FLOT图表插件使用。
至少,FLOT的JSON数据必须是数字数组,即
[ [x1, y1], [x2, y2], ... ]
给定我有一个Java中的Point对象的列表,即
List<Point> data = new ArrayList<>();
点定义为
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格式的Java对象。目前,我正在以这种格式输出:
[{x:x1, y:y1}, {x:x2, y:y2} ...]
当我需要这种格式时:
[[x1,y1], [x2,y2] ...]
您可以编写自定义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]]
希望这可以帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句