簡體   English   中英

如何使用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)));
}

谷歌搜索我找到了解決方案。 我們可以使用最新的Jackson API(2.9.7)使用@JsonAlias因此,在我的情況下,我希望使用此別名來反序列化@JsonAlias(value={"author","authorList"})

JSON Jackson將不同的密鑰解析到同一字段中

您還可以將此功能添加到objectMapper中:

DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM