简体   繁体   中英

jackson deserialize array into a java object

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 would like to use jackson magic to get a list of instances of

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

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

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 )

=== 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 + '\'' + '}';
    }
}

Add following annotation:

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

and it should serialize entries as you wish.

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.

Consider importing the two dimensional array and then running through a loop. Then you can have a constructor on the Endpoint class that accepts each instance of internal array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM