jackson将数组反序列化为java对象

jackson将数组反序列化为java对象

问题描述:

我有json的主机,端口,uri 数组由第三方编码为固定长度数组的数组:

I have json'ed array of host, port, uri tuples encoded by 3rd party as an array of fixed length arrays:

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

I想使用jackson magic来获取

I would like to use jackson magic to get a list of instances of

class Endpoint {
    String host;
    int port;
    String uri;
}

请帮我添加正确的注释,让ObjectMapper发挥神奇的作用。

Please help me to put proper annotations to make ObjectMapper to do the magic.

我无法控制传入的格式,所有关于如何将适当的json对象(不是数组)数组映射到对象列表的答案中我的所有google'n都结束了例如 https://stackoverflow.com/a/6349488/707608

I do not have control on the incoming format and all my google'n ends in answers on how to map array of proper json objects (not arrays) into list of objects (like https://stackoverflow.com/a/6349488/707608)

=== https://stackoverflow.com/users/59501/staxman 建议的工作解决方案
https://stackoverflow.com/a/38111311/707608

=== working solution as advised by https://stackoverflow.com/users/59501/staxman in 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 {
}

并且它应该按照您的意愿序列化条目。

and it should serialize entries as you wish.

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

Also: it'd be safest to then use @JsonPropertyOrder({ .... } ) to enforce specific ordering, as JVM may or may not expose fields or methods in any specific order.