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

我有一个 Java 对象“作者”,然后它被重组为“作者”的 Ararylist。Author 对象直接作为 JSON 保存在 DB 中,如下所示:


{"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)


慕莱坞森
浏览 160回答 3
3回答

精慕HU

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

拉莫斯之舞

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

肥皂起泡泡

如果您只需要使用“author”属性进行反序列化,最简单的方法就是为其提供将要查找的 setter 方法。例如:@JsonProperty("author")public void setAuthor(Author author) {&nbsp; &nbsp; setAuthorList(new ArrayList<>(Collections.singletonList(author)));}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java