我有由第三方编码为固定长度数组的jsont_code元组的json'ed数组:

[
  ["www1.example.com", "443", "/api/v1"],
  ["proxy.example.com", "8089", "/api/v4"]
]

我想使用 jackson 魔术来获取的实例列表
class Endpoint {
    String host;
    int port;
    String uri;
}

请帮助我放置适当的注释,以使ObjectMapper发挥作用。

我无法控制传入的格式,而我所有的google'n都以答案来回答如何将适当的json对象(而非数组)数组映射到对象列表(如https://stackoverflow.com/a/6349488/707608)

=== https://stackoverflow.com/users/59501/staxman建议的工作解决方案
https://stackoverflow.com/a/38111311/707608
public static void main(String[] args) throws IOException {
    String input = "" +
            "[\n" +
            "  [\"www1.example.com\", \"443\", \"/api/v1\"],\n" +
            "  [\"proxy.example.com\", \"8089\", \"/api/v4\"]\n" +
            "]";

    ObjectMapper om = new ObjectMapper();
    List<Endpoint> endpoints = om.readValue(input,
        new TypeReference<List<Endpoint>>() {});

    System.out.println("endpoints = " + endpoints);
}

@JsonFormat(shape = JsonFormat.Shape.ARRAY)
static class Endpoint {
    @JsonProperty() String host;
    @JsonProperty() int port;
    @JsonProperty() String uri;

    @Override
    public String toString() {
        return "Endpoint{host='" + host + '\'' + ", port='" + port + '\'' + ", uri='" + uri + '\'' + '}';
    }
}

最佳答案

添加以下注释:

@JsonFormat(shape=JsonFormat.Shape.ARRAY)
class Endpoint {
}

并且它应该根据需要序列化条目。

另外:然后,最安全的方法是使用@JsonPropertyOrder({ .... } )强制执行特定的顺序,因为JVM可能会也可能不会以任何特定的顺序公开字段或方法。

10-02 03:17
查看更多