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