Jackson自定義轉換器

在使用各類json序列化工具的時候常常會碰到抽象類的問題json

設計接口時,想統一接口,老是想要傳遞抽象參數,可是json的反序列化老是很讓人悲傷ide

還好對於Jackson咱們有個利器,能夠自定義咱們的轉換器Converter工具

首先咱們須要指定反序列化要使用的轉換器,經過註解@JsonDeserialize(converter = ProductConverter.class) 該註解能夠放到class、field、和set方法上this

轉換器代碼以下spa

 

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);
    }
}
相關文章
相關標籤/搜索