如何在序列化时将DataPoint对象转为二维数组(无需自定义序列化器)
问题:无需自定义序列化器实现Jackson嵌套对象转二维数组序列化
目标JSON结构
"entries" : [ { "name" : "<name>", "dataPoint" : [ [1681792679186, 1096.0], [1681792680186, 1147.0] ] } ]
每个数据点是包含long和double类型的二元数组。
现有Java代码
public class Entry { private String name; private List<DataPoint> dataPoint; // constructor and getters omitted } public class DataPoint{ List<?> data; public DataPoint(long date, double counts) { this.data = List.of(date, counts); } public List<?> getDataPoint() { return data; } }
当前序列化结果
{ "name" : "20070480", "data" : [ { "dataPoint" : [ 1681792679186, 1096.0 ] }, { "dataPoint" : [ 1681792680186, 1147.0 ] } ] }
需求是让dataPoint直接对应二维数组,而非嵌套对象数组,且不使用自定义序列化器。
解决方案
方案一:移除DataPoint包装类,直接使用二维列表
直接修改Entry类的dataPoint类型为List<List<?>>,跳过DataPoint的包装层,序列化时自然生成目标二维数组结构:
public class Entry { private String name; private List<List<?>> dataPoint; public Entry(String name, List<List<?>> dataPoint) { this.name = name; this.dataPoint = dataPoint; } // getters omitted }
使用时直接构造二元数组添加到列表:
List<List<?>> points = new ArrayList<>(); points.add(List.of(1681792679186L, 1096.0)); points.add(List.of(1681792680186L, 1147.0)); Entry entry = new Entry("20070480", points);
方案二:保留DataPoint类,使用@JsonValue注解
如果必须保留DataPoint类,在其返回数据的方法上添加@JsonValue注解,告诉Jackson直接序列化该方法返回的内容,而非序列化整个DataPoint对象:
public class DataPoint{ List<?> data; public DataPoint(long date, double counts) { this.data = List.of(date, counts); } @JsonValue public List<?> getDataPoint() { return data; } }
同时确保Entry类的dataPoint字段名称与JSON目标字段一致(默认命名策略下,字段dataPoint的gettergetDataPoint()会序列化为dataPoint字段)。这样每个DataPoint对象会被直接序列化为对应的二元数组,最终得到目标结构。
内容的提问来源于stack exchange,提问作者Peter Kronenberg
相关产品推荐
相关产品推荐

