杰克逊2支持版本控制 [英] Jackson 2 support for versioning

查看:127
本文介绍了杰克逊2支持版本控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

杰克逊模型版本控制模块添加版本支持,满足GSON的@Since和@Until的超级集。

The Jackson Model Versioning Module adds versioning support which satisfies a super-set of GSON's @Since and @Until.

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

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;
}

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

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()));
    }
}

现在只需使用模块和测试配置Jackson ObjectMapper它出来了。

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"}'






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

这篇关于杰克逊2支持版本控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆