杰克逊2支持版本控制

Nir*_*jan 8 jackson

有谁知道Jackson2是否支持版本控制; 类似于GSON @Since@Until注释的东西?

Jon*_*son 9

杰克逊型号版本模块增加了版本支持满足超集GSON的@Since和@Until的.


假设您有一个带GSON注释的模型:

public class Car {
    public String model;
    public int year;
    @Until(1) public String new;
    @Since(2) public boolean used;
}
Run Code Online (Sandbox Code Playgroud)

使用该模块,您可以将其转换为以下Jackson类级别注释...

@JsonVersionedModel(currentVersion = '3', toCurrentConverterClass = ToCurrentCarConverter)
public class Car {
    public String model;
    public int year;
    public boolean used;
}
Run Code Online (Sandbox Code Playgroud)

...并编写一个当前版本的转换器:

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()));
    }
}
Run Code Online (Sandbox Code Playgroud)

现在只需使用模块配置Jackson ObjectMapper并测试它.

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"}'
Run Code Online (Sandbox Code Playgroud)

免责声明:我是本单元的作者.有关其他功能的更多示例,请参阅GitHub项目页面.我还编写了一个Spring MVC ResponseBodyAdvise来使用该模块.


Sta*_*Man 2

不直接。您可以使用@JsonViewJSON Filter 功能来实现类似的包含/排除。