我有一段 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 类的属性。使用 Jackson 是否可能实现这样的功能?
更新
通过自定义反序列化器解决了这个问题:
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 的建议。