Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jackson deserialize array into a java object

Tags:

java

json

jackson

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 + '\'' + '}';
    }
}
like image 961
ya_pulser Avatar asked Jul 14 '26 08:07

ya_pulser


1 Answers

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.

like image 122
StaxMan Avatar answered Jul 15 '26 22:07

StaxMan