【Java】修复”com.alibaba.fastjson.JSONObject cannot be cast to”报错问题

报错如下:

java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to com.coding.lable.dto.HealthFilterNodeDtoat com.coding.lable.service.impl.ReptLabelsServiceImpl.filterFormulaCompute(ReptLabelsServiceImpl.java:240)at com.coding.lable.service.impl.ReptLabelsServiceImpl.lambda$labelUserRept$1(ReptLabelsServiceImpl.java:187)at java.util.ArrayList.forEach(ArrayList.java:1257)at com.coding.lable.service.impl.ReptLabelsServiceImpl.labelUserRept(ReptLabelsServiceImpl.java:168)at com.coding.lable.service.impl.ReptLabelsServiceImpl$$FastClassBySpringCGLIB$$e754d10b.invoke(<generated>)at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366)at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)

通过 debug 断点可以看到,这里拿到虽然是 List,但是里面的对象还是一个 JSONObject,并不是需要的 DTO 类,所有导致了后面的报错。

// 反序列化List<HealthFilterNodeDto> expressions = (List<HealthFilterNodeDto>) JSON.parse(filterFormula.getExpression());healthFilterFormulaDto.setExpressions(expressions);


查到问题根源,只要把这里的对象转化为 DTO 类就行了,就可以避免报错。

增加代码:

// 反序列化List<HealthFilterNodeDto> expressions = JSON.parseArray(JSON.toJSONString(filterFormula.getExpression()), HealthFilterNodeDto.class);healthFilterFormulaDto.setExpressions(expressions);

我的json "[{},{}]" 已经存为字符串所以改写这样:

List<HealthFilterNodeDto> expressions = new ArrayList<>(JSON.parseArray(filterFormula.getExpression(), HealthFilterNodeDto.class));healthFilterFormulaDto.setExpressions(expressions);