如何使用 Jackson API 在序列化和反序列化中使用不同的 JSONProperty?

How to use different JSONProperty on Serialize & Deserialize using Jackson API?

我有一个 Java 对象“Author”,然后将其重组为 "Author" 的 Ararylist。作者对象直接保存在数据库中,如下所示 JSON:

{"author":{"id":1,"recordId":0}}

所以我之前的 Java 字段是:

private Author author = new Author();

新的是:

private List<Author> authorList;

问题是我如何编写代码以使用 authorList 序列化对象,但还需要反序列化旧的“Author”。

我使用 @JsonProperty 读取已保存的 author 数据,但这也保存了名为 "Author" 的 Arraylist,我需要将其命名为 authorList

@JsonProperty(value="author")
@JsonDeserialize(using = AuthorDeserializer.class)

如果你只需要用 "author" 属性 反序列化,最简单的方法就是给它提供它要查找的 setter 方法。

例如:

@JsonProperty("author")
public void setAuthor(Author author) {
    setAuthorList(new ArrayList<>(Collections.singletonList(author)));
}

谷歌搜索我找到了解决方案。 我们可以使用 @JsonAlias 使用最新的 Jackson API (2.9.7) 所以在我的例子中,我想要这个反序列化的别名 @JsonAlias(value={"author","authorList"}).

JSON Jackson parse different keys into same field

您还可以将此功能添加到您的 objectMapper:

DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY