Deserialisieren verschachtelten Array als ArrayList mit Jackson

Habe ich ein Stück von JSON sieht wie folgt aus:

{
  "authors": {
    "author": [
      {
        "given-name": "Adrienne H.",
        "surname": "Kovacs"
      },
      {
        "given-name": "Philip",
        "surname": "Moons"
      }
    ]
   }
 }

Habe ich eine Klasse zum speichern von Informationen zum Autor:

public class Author {
    @JsonProperty("given-name")
    public String givenName;
    public String surname;
}

Und zwei wrapper-Klassen:

public class Authors {
    public List<Author> author;
}

public class Response {
    public Authors authors;
}

Diese arbeitet, aber mit zwei wrapper-Klassen zu sein scheint, unnötig. Ich möchte einen Weg finden, zu entfernen Authors Klasse und haben eine Liste als Eigenschaft der Einstiegsklasse. Ist sowas möglich ist mit Jackson?

Update

Gelöst, dass mit benutzerdefinierten deserializer:

public class AuthorArrayDeserializer extends JsonDeserializer<List<Author>> {

    private static final String AUTHOR = "author";
    private static final ObjectMapper mapper = new ObjectMapper();
    private static final CollectionType collectionType =
            TypeFactory
            .defaultInstance()
            .constructCollectionType(List.class, Author.class);

    @Override
    public List<Author> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
            throws IOException, JsonProcessingException {

        ObjectNode objectNode = mapper.readTree(jsonParser);
        JsonNode nodeAuthors = objectNode.get(AUTHOR);

        if (null == nodeAuthors                     //if no author node could be found
                || !nodeAuthors.isArray()           //or author node is not an array
                || !nodeAuthors.elements().hasNext())   //or author node doesn't contain any authors
            return null;

        return mapper.reader(collectionType).readValue(nodeAuthors);
    }
}

Und verwenden Sie es wie folgt:

@JsonDeserialize(using = AuthorArrayDeserializer.class)
public void setAuthors(List<Author> authors) {
    this.authors = authors;
}

Dank @wassgren für die Idee.

InformationsquelleAutor der Frage Dmitry | 2015-01-12

Schreibe einen Kommentar