反序列化嵌套数组为 ArrayList 与 Jackson更新
我有一段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;
}
这是有效的,但拥有两个包装类似乎是不必要的。我想找到一种方法来删除类,并将列表作为 Entry 类的属性。杰克逊有可能这样的事情发生吗?Authors
更新
使用自定义反序列化程序解决了这个问题:
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的想法。