在使用各种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); } }