Does anyone know if Jackson2 supports versioning; something similar to GSON's @Since
and @Until
annotations?
The Jackson Model Versioning Module adds versioning support which satisfies a super-set of GSON's @Since and @Until.
Lets say you have a GSON-annotated model:
public class Car {
public String model;
public int year;
@Until(1) public String new;
@Since(2) public boolean used;
}
Using the module, you could convert it to the following Jackson class-level annotation...
@JsonVersionedModel(currentVersion = '3', toCurrentConverterClass = ToCurrentCarConverter)
public class Car {
public String model;
public int year;
public boolean used;
}
...and write a to-current-version converter:
public class ToCurrentCarConverter implements VersionedModelConverter {
@Override
public ObjectNode convert(ObjectNode modelData, String modelVersion,
String targetModelVersion, JsonNodeFactory nodeFactory) {
// model version is an int
int version = Integer.parse(modelVersion);
// version 1 had a 'new' text field instead of a boolean 'used' field
if(version <= 1)
modelData.put("used", !Boolean.parseBoolean(modelData.remove("new").asText()));
}
}
Now just configure the Jackson ObjectMapper with the module and test it out.
ObjectMapper mapper = new ObjectMapper().registerModule(new VersioningModule());
// version 1 JSON -> POJO
Car hondaCivic = mapper.readValue(
"{\"model\": \"honda:civic\", \"year\": 2016, \"new\": \"true\", \"modelVersion\": \"1\"}",
Car.class
)
// POJO -> version 2 JSON
System.out.println(mapper.writeValueAsString(hondaCivic))
// prints '{"model": "honda:civic", "year": 2016, "used": false, "modelVersion": "2"}'
Disclaimer: I am the author of this module. See the GitHub project page for more example of additional functionality. I have also written a Spring MVC ResponseBodyAdvise for using the module.
Not directly. You could use @JsonView
or JSON Filter functionality for implementing similar inclusion/exclusion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With