Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson 2 support for versioning

Tags:

jackson

Does anyone know if Jackson2 supports versioning; something similar to GSON's @Since and @Until annotations?

like image 950
Niranjan Avatar asked Jan 17 '14 19:01

Niranjan


2 Answers

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.

like image 186
Jon Peterson Avatar answered Oct 30 '22 21:10

Jon Peterson


Not directly. You could use @JsonView or JSON Filter functionality for implementing similar inclusion/exclusion.

like image 40
StaxMan Avatar answered Oct 30 '22 23:10

StaxMan