【Java】修复"com.alibaba.fastjson.JSONObject cannot be cast to"报错问题
报错如下:
java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to com.coding.lable.dto.HealthFilterNodeDto
at 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 类就行了,就可以避免报错。
增加代码:文章来源:https://www.toymoban.com/news/detail-543354.html
// 反序列化
List<HealthFilterNodeDto> expressions = JSON.parseArray(JSON.toJSONString(filterFormula.getExpression()), HealthFilterNodeDto.class);
healthFilterFormulaDto.setExpressions(expressions);
我的json "[{},{}]"
已经存为字符串所以改写这样:文章来源地址https://www.toymoban.com/news/detail-543354.html
List<HealthFilterNodeDto> expressions = new ArrayList<>(JSON.parseArray(filterFormula.getExpression(), HealthFilterNodeDto.class));
healthFilterFormulaDto.setExpressions(expressions);
到了这里,关于【Java】“com.alibaba.fastjson.JSONObject cannot be cast to“报错问题的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!