Here an easy example: Suppose I have two classes, MyEntity and Person:
public class MyEntity {
long id;
String name;
}
public class Person extends MyEntity {
String lastName;
int age;
// other fields
}
So far no problem. Now I want them to be parsed to JSON using Jackson annotations. Supposing I have many other entities that extend MyEntity and all of them have the JSON field name
but particularly name
must be parsed to lastName
in Person
class. Is there any way to do that? What would be logical for me would be an annotation like (I made up this code!! just to get the idea):
@JSONFieldValue(subClass = Person.class, field = "name", JSONName = "lastName")
public class MyEntity{}
Do you guys know of any way to achieve something like this?
Thanks in advance!
Jackson by default uses setter methods for deserializing and infers the JSON field name by the setter method name according to Java beans conventions.
To parse a JSON field named name
into a Java class field named lastName
just add this setter at Person
:
void setName(String name) {
lastName = name;
}
or annotate the normal setter in Person
:
@JsonProperty( "name" )
void setLastName(String lastName) {
this.lastName = lastName;
}