1、如何可以修改相关反序列化类代码,就加上默认构造方法。
2、如果不能修改相关类代码,就利用如下工具类,给反序列化错误的那个类指定一个构造方法。
package com.me.best.mock.utils;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer;
import com.alibaba.fastjson.util.FieldInfo;
import com.alibaba.fastjson.util.JavaBeanInfo;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
public class FastJsonStrengthen {
public static void addTypeInstance(Class<?> clazz, BiFunction biFunction) {
ParserConfig parserConfig = ParserConfig.getGlobalInstance();
List<FieldInfo> fieldList = new ArrayList<>();
for (Class<?> currentClass = clazz; currentClass != null; currentClass = currentClass.getSuperclass()) {
Field[] fields = currentClass.getDeclaredFields();
try {
Class<JavaBeanInfo> javaBeanInfoClass = JavaBeanInfo.class;
String methodName = "computeFields";
Method computeFields = getMethod(javaBeanInfoClass, methodName);
computeFields.setAccessible(true);
computeFields.invoke(null, clazz, clazz, parserConfig.propertyNamingStrategy, fieldList, fields);
} catch (Exception e) {
e.printStackTrace();
}
}
JavaBeanInfo javaBeanInfo = new JavaBeanInfo(clazz, clazz, null, null, null, null, null, fieldList);
JavaBeanDeserializer deserializer = new JavaBeanDeserializer(parserConfig, javaBeanInfo){
@Override
public Object createInstance(DefaultJSONParser parser, Type type) {
return biFunction.apply(parser, type);
}
};
parserConfig.putDeserializer(clazz,
deserializer);
}
public static Method getMethod(Class clazz, String methodName) {
Method[] methods = clazz.getDeclaredMethods();
Method computeFields = null;
for (Method method : methods) {
if (method.getName().equals(methodName)) {
computeFields = method;
}
}
return computeFields;
}
}
使用样例
FastJsonStrengthen.addTypeInstance(User.class, (parser, type)->{
User user2 = User.build();
return user2;
});