3

I had a Java object "Author" which was then restructured to become an Ararylist of "Author". Author object was saved in DB directly as JSON below:

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

So my earlier Java Field was :

private Author author = new Author();

and new is :

private List<Author> authorList;

Problem is how i can write my code to have Serialized object with authorList but need to deserialize old "Author" as well.

I used @JsonProperty to read already saved author data but this also saves Arraylist named "Author" which i need to name as authorList

@JsonProperty(value="author")
@JsonDeserialize(using = AuthorDeserializer.class)
usman
  • 1,351
  • 5
  • 23
  • 47

3 Answers3

2

Googling around i have found solution for it. We can use @JsonAlias using latest Jackson API (2.9.7) So in my case i wanted this alias for deserialization @JsonAlias(value={"author","authorList"}).

JSON Jackson parse different keys into same field

usman
  • 1,351
  • 5
  • 23
  • 47
1

You can also add this feature to your objectMapper:

DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY
Selindek
  • 3,269
  • 1
  • 18
  • 25
0

If you only need to deserialize with the "author" property, the simplest way is just to give it the setter method it will be looking for.

For example:

@JsonProperty("author")
public void setAuthor(Author author) {
    setAuthorList(new ArrayList<>(Collections.singletonList(author)));
}
df778899
  • 10,703
  • 1
  • 24
  • 36
  • On serializing Author it should save as "authorList" and not "author" i.e. JSON shall save as "authorList":"[{data}]" and deserialize both old and new keys "author" & "authorList" – usman Oct 02 '18 at 10:45
  • Yes. it works that way. Of course you need the authorList property too with getter and setter. Because there is only one getter: only authorList will be serialized, but because there is an other setter for author, both version will be deserialized correctly. – Selindek Oct 02 '18 at 14:52