@JsonAnySetter annotation can be used to define "any setter" mutator. It is used on a non-static two-argument method; first argument is name of property and the second one, is the value of the property. It can also be used on a field (of type Map or POJO). It acts as a "fallback" handler for all otherwise unmapped properties found in input JSON content. It is the counterpart to "any getter" (see @JsonAnyGetter).
Example
POJO
public class ScreenInfo {
private String id;
private String title;
private int width;
private int height;
private Map<String, Object> otherInfo;
......
@JsonAnySetter
public void addOtherInfo(String propertyKey, Object value) {
if (this.otherInfo == null) {
this.otherInfo = new HashMap<>();
}
this.otherInfo.put(propertyKey, value);
}
.....
}
Deserializing JSON
public class MainScreenInfoDeSerialization {
public static void main(String[] args) throws IOException {
String jsonString = "{\"id\":\"TradeDetails\",\"title\":\"Trade Details\","
+ "\"width\":500,\"height\":300,\"xLocation\":400,\"yLocation\":200}";
System.out.println("-- before deserialization --");
System.out.println(jsonString);
ObjectMapper om = new ObjectMapper();
ScreenInfo screenInfo = om.readValue(jsonString, ScreenInfo.class);
System.out.println("-- after deserialization --");
System.out.println(screenInfo);
}
} -- before deserialization -- {"id":"TradeDetails","title":"Trade Details","width":500,"height":300,"xLocation":400,"yLocation":200} -- after deserialization -- ScreenInfo{id='TradeDetails', title='Trade Details', width=500, height=300, otherInfo={xLocation=400, yLocation=200}}
Without @JsonAnySetter
If we remove @JsonAnySetter from ScreenInfo#addOtherInfo() method then output will be:
-- before deserialization --
{"id":"TradeDetails","title":"Trade Details","width":500,"height":300,"xLocation":400,"yLocation":200}
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "xLocation" (class com.logicbig.example.ScreenInfo), not marked as ignorable (4 known properties: "title", "id", "width", "height"])
....
Example ProjectDependencies and Technologies Used: - jackson-databind 2.9.6: General data-binding functionality for Jackson: works on core streaming API.
- JDK 10
- Maven 3.5.4
|
|