Tôi có một mảnh JSON, trông như thế này:Deserialize mảng lồng nhau như ArrayList với Jackson
{
"authors": {
"author": [
{
"given-name": "Adrienne H.",
"surname": "Kovacs"
},
{
"given-name": "Philip",
"surname": "Moons"
}
]
}
}
Tôi đã tạo ra một lớp học để lưu trữ thông tin Tác giả:
public class Author {
@JsonProperty("given-name")
public String givenName;
public String surname;
}
Và hai lớp wrapper :
public class Authors {
public List<Author> author;
}
public class Response {
public Authors authors;
}
Điều này đang hoạt động nhưng có hai lớp trình bao bọc dường như không cần thiết. Tôi muốn tìm cách xóa lớp Authors
và có danh sách là thuộc tính của lớp Nhập. Có chuyện như thế có thể xảy ra với Jackson không?
Cập nhật
Giải Quyết rằng với tùy chỉnh 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);
}
}
Và sử dụng nó như thế này:
@JsonDeserialize(using = AuthorArrayDeserializer.class)
public void setAuthors(List<Author> authors) {
this.authors = authors;
}
Cảm ơn @wassgren cho ý tưởng.
trả lời giúp bạn –