Jackson自定义转换器

在使用各种json序列化工具的时候经常会碰到抽象类的问题

设计接口时,想统一接口,总是想要传递抽象参数,但是json的反序列化总是很让人悲伤

还好对于Jackson我们有个利器,可以自定义我们的转换器Converter

首先我们需要指定反序列化要使用的转换器,通过注解@JsonDeserialize(converter = ProductConverter.class) 该注解可以放到class、field、和set方法上

转换器代码如下

 

public class ProductConverter implements Converter<JsonNode, Product> {

    @Override
    public Product convert(JsonNode value) {
        JsonNode productCategoryNode = value.get("productCategory");
        if (null == productCategoryNode) {
            final JsonNode id = value.get("id");
            if (null == id) {
                throw new RuntimeException("product not has needed property id : " + value);
            }
            return new Product() {@Override public String getId() {return id.textValue();}};//simple product
        }
        Product product = parseProduct(value, productCategoryNode);
        return product;
    }

    /**
     * 根据类型生成具体实体对象
     */
    private Product parseProduct(JsonNode value, JsonNode productCategoryNode) {
        Product product = null;
        ProductCategory productCategory = ProductCategory.valueOf(productCategoryNode.textValue());
        switch (productCategory) {
            case BILL:
                product = new BillProduct();
                break;
            case FUND:
                product = new FundProduct();
                break;
            default:
                throw new RuntimeException("cannot support this category now:" + productCategory.name());
        }
        BeanCopy.fromMap(JSONUtil.fromJson(value.toString(), HashMap.class)).toBean(product).ignoreNulls(true).copy();
        return product;
    }


    @Override
    public JavaType getInputType(TypeFactory typeFactory) {
        return typeFactory.constructType(JsonNode.class);
    }

    @Override
    public JavaType getOutputType(TypeFactory typeFactory) {
        return typeFactory.constructType(Product.class);
    }
}

 

转载于:https://www.cnblogs.com/mutouyaya/p/4874650.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值