ya_pulser ya_pulser - 1 year ago 247
JSON Question

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 http://stackoverflow.com/a/6349488/707608)

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

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

Answer Source

Add following annotation:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download