spring 3+ fastjson bug 记录
程序员文章站
2022-05-09 12:14:43
...
场景描述:
使用fastjson的JSON.toJSONString(Domain)的时候,如果Domain中有字段是通过spring proxy出来的,在spring3以上版本会报错,spring3以下不受影响:代理代码如下:
ProxyFactory proxy = new ProxyFactory(Manager); proxy.addAdvice(Interceptor); return (VO) proxy.getProxy();
报错如下:
Caused by: com.alibaba.fastjson.JSONException: create asm serializer error, class interface org.springframework.aop.Advisor at com.alibaba.fastjson.serializer.SerializeConfig.createJavaBeanSerializer(SerializeConfig.java:88) at com.alibaba.fastjson.serializer.JSONSerializer.getObjectWriter(JSONSerializer.java:455) at com.alibaba.fastjson.serializer.JSONSerializer.getObjectWriter(JSONSerializer.java:423) at com.alibaba.fastjson.serializer.JSONSerializer.writeWithFieldName(JSONSerializer.java:371) at Serializer_6.write1(Unknown Source) at Serializer_6.write(Unknown Source) at com.alibaba.fastjson.serializer.JSONSerializer.writeWithFieldName(JSONSerializer.java:373) at Serializer_2.write1(Unknown Source) at Serializer_2.write(Unknown Source) at com.alibaba.fastjson.serializer.JSONSerializer.write(JSONSerializer.java:352) at com.alibaba.fastjson.JSON.toJSONString(JSON.java:378) at com.alibaba.fastjson.JSON.toJSONString(JSON.java:366) Caused by: java.lang.NullPointerException at com.alibaba.fastjson.util.TypeUtils.isJSONTypeIgnore(TypeUtils.java:952) at com.alibaba.fastjson.util.TypeUtils.isJSONTypeIgnore(TypeUtils.java:963) at com.alibaba.fastjson.util.TypeUtils.computeGetters(TypeUtils.java:827)
原理:
spring3以后spring-CORE 里面包含了CGLIB,相关类由
net.sf.cglib.proxy.Factory
变为: org.springframework.cglib.proxy.Factory
假设Domain里面的A这个对象,通过A.getInterface[] 可以看到
spring 3: (java.lang.Class<T>[]) [interface org.springframework.aop.SpringProxy, interface org.springframework.aop.framework.Advised, interface org.springframework.cglib.proxy.Factory] spring 2: (java.lang.Class<T>[]) [interface org.springframework.aop.SpringProxy, interface org.springframework.aop.framework.Advised, interface net.sf.cglib.proxy.Factory]
而在fastjsom:JSONSerializer的 472行(21版本)
for (Class<?> item : clazz.getInterfaces()) { if (item.getName().equals("net.sf.cglib.proxy.Factory")) { isCglibProxy = true; break; } else if (item.getName().equals("javassist.util.proxy.ProxyObject")) { isJavassistProxy = true; break; } }
这里会判断失效。导致问题。
后续
已报告fastjson团队,目前1.1.40版本任未修复。