您只需要 Coordinate 类上的 2 个简单注释:
@JsonFormat(shape = Shape.ARRAY)
@JsonPropertyOrder({"x", "y"})
public static class Coordinate {
public double x;
public double y;
public Coordinate() {}
public Coordinate(double x, double y) {
this.x = x;
this.y = y;
}
}
public void test() throws IOException {
List<Coordinate> p = new ArrayList<Coordinate>();
p.add(new Coordinate(1, 2));
p.add(new Coordinate(3, 4));
ObjectMapper mapper = new ObjectMapper();
String writeValueAsString = mapper.writeValueAsString(p);
System.out.println(writeValueAsString);
CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Coordinate.class);
List<Coordinate> readValue = mapper.readValue(writeValueAsString, collectionType);
assertEquals(readValue.size(), 2);
assertEquals(readValue.get(0).x, 1, 0.0);
assertEquals(readValue.get(0).y, 2, 0.0);
assertEquals(readValue.get(1).x, 3, 0.0);
assertEquals(readValue.get(1).y, 4, 0.0);
}
不涉及中间过程,杰克逊为您完成所有工作。@JsonFormat 注释告诉 Jackson 你期望的是一个数组而不是一个对象,@JsonPropertyOrder 确保属性总是以正确的顺序解码。这还有一个额外的好处,您甚至可以使用相同的格式对数据进行编码!
如果您无权访问 Coordinate 类来添加这些注释,只需使用 Jackson 的混合功能。