Jackson2 Java to Json array ignore field names when creating array

只谈情不闲聊 提交于 2019-12-06 05:57:56

You can write a custom Point serializer

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();
    }
}

then you can set your custom serializer class to your Point class

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;
    }
}

and try it

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

the code produces the following result

[[1,2],[2,3]]

hope this helps.

You can use the @JsonView annotation on a special getter method which returns an array of intergers. Here is an example:

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)));
    }

}

Output:

[ 12, 45 ]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!