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

【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()
	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 expressions = (List) JSON.parse(filterFormula.getExpression());
healthFilterFormulaDto.setExpressions(expressions);

在这里插入图片描述

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

增加代码:

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

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

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

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/f281f46ed5.html