gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:23:53 26 4
gpt4 key购买 nike

我正在尝试创建一个 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 注释(如果有)放在 Java 对象上以获得正确的 JSON 格式。目前我得到这种格式的输出:

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

当我需要这种格式时:

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

最佳答案

您可以在返回整数数组的特殊 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 ]

关于java - Jackson2 Java 到 Json 数组在创建数组时忽略字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23344099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com