@JsonSetter
@JsonSetter is an alternative to @JsonProperty - used to mark the method as a setter method.
This is super useful when we need to read some JSON data but the target entity class doesn't exactly match that data, and so we need to tune the process to make it fit.
In the following example, we'll specify the method setTheName() as the setter of the name property in our MyBean entity:
public class MyBean2 {
private int id;
private String name;
@JsonSetter("name")
public void setTheName(String name) {
this.name = name;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "MyBean2{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
Now, when we need to unmarshall some JSON data - this works perfectly well:
@Test
public void test02() throws Exception {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"id\":1,\"name\":\"My bean\"}";
MyBean2 myBean2 = mapper.readValue(json, MyBean2.class);
System.out.println(myBean2);
}