Mybatis-Plus中使用JacksonTypeHandler报错java.util.LinkedHashMap cannot be cast to xxx

  • A+
所属分类:mybatis mysql

背景:mysql中的一个字段类型为json,使用mybatis-plus,entity中该字段定义为List<CusDTO> extra,并指定了注解

@TableField(typeHandler = JacksonTypeHandler.class)

数据插入进去是没问题的,但是取出来时,循环处理时,报错java.util.LinkedHashMap cannot be cast to CusDTO

研究了下,发现JacksonTypeHandler只能用于单个对象的json序列化,而List类型的,由于它并不知道具体的泛型是哪个,所以就当做Map来处理了,所以循环时才会报类型转换的错。

解决方法是自定义一个TypeHandler,里面明确指定泛型,并使用jaskon中列表的序列化方式。代码如下:

@MappedTypes({List.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ListJacksonTypeHandler extends AbstractJsonTypeHandler<List> {
    private final ObjectMapper objectMapper;
    private final CollectionType collectionType;

    public ListBalanceAcctJacksonTypeHandler() {
        this.objectMapper = JacksonUtil.getBuilder().build();
        this.collectionType = this.objectMapper.getTypeFactory()
                .constructCollectionType(ArrayList.class, CusDTO.class);
    }

    @Override
    protected List parse(String json) {
        try {
            return objectMapper.readValue(json, collectionType);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected String toJson(List obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}

 

ZPY

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: