У меня есть часть JSON, которая выглядит так:
{
"authors": {
"author": [
{
"given-name": "Adrienne H.",
"surname": "Kovacs"
},
{
"given-name": "Philip",
"surname": "Moons"
}
]
}
}
Я создал класс для хранения информации об авторе:
public class Author {
@JsonProperty("given-name")
public String givenName;
public String surname;
}
И два класса оболочки:
public class Authors {
public List<Author> author;
}
public class Response {
public Authors authors;
}
Это работает, но наличие двух классов-оболочек кажется ненужным. Я хочу найти способ удалить класс Authors
и иметь список как свойство класса Entry. Возможно ли подобное с Джексоном?
Update
Решено, что с пользовательским десериализатором:
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);
}
}
И используя его вот так:
@JsonDeserialize(using = AuthorArrayDeserializer.class)
public void setAuthors(List<Author> authors) {
this.authors = authors;
}
Спасибо @wassgren за эту идею.