Jackson2 Java到Json数组在创建数组时忽略字段名称

时间:2014-04-28 14:43:27

标签: java arrays json jackson jsonserializer

我试图创建一个Java REST端点,它返回一个JSON数据数组,供JQuery FLOT图表插件使用。

至少,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;
    }

    ...
 }

我需要在Java对象上使用哪些方法或Jackson2注释(如果有)来获取正确的JSON格式。目前我正在以这种格式获得输出:

[{x:x1, y:y1}, {x:x2, y:y2} ...]

当我需要这种格式时:

[[x1,y1], [x2,y2] ...]

2 个答案:

答案 0 :(得分:2)

您可以在特殊的getter方法上使用@JsonView批注,该方法返回一个整数数组。这是一个例子:

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 ]

答案 1 :(得分:1)

您可以编写自定义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]]

希望这会有所帮助。