现有一需求将实体对应属性的json解析写入到对应实体的字段属性中,对应属性较复杂(包含实体和list<E>等)。
方法如下:
已知实体以及每个属性字段所对应的值为复杂json存入map当中。然后将所有对应的值解析转换到对应实体的字段属性中。
代码如下:
private static <T> T transformMapToSjmhReportResultData(Map<String, Object> hashMap, Class<T> cls)
throws IOException, IntrospectionException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException, InstantiationException, NoSuchMethodException, SecurityException {
//创建一个类的实体,用于保存map,后期返回
Field[] fs = cls.getDeclaredFields(); // 得到所有的fields
Gson gson = new Gson();
Constructor<T> constructor = cls.getConstructor();//获得此类的构造方法
T t = constructor.newInstance();//获取对应的实例
for (Field f : fs) {
f.setAccessible(true);//将访问私有属性设置为可访问,否则私有化属性将无法成功写入
Class fieldClazz = f.getType(); // 得到field的class及类型全路径
if (fieldClazz.isPrimitive()) {
continue; //1 判断是否为基本类型
}
if (fieldClazz.getName().startsWith("java.lang")) {
continue; //getName()返回field的类型全路径;
}
for (String key : hashMap.keySet()) {
if (f.getName().equals(key)) {
String value = hashMap.get(key).toString();
// String valueStr = GzipUtil.unCompress(value);
if (fieldClazz.isAssignableFrom(List.class)) { //判断是否为list类型
Type fc = f.getGenericType(); // 2关键的地方,如果是List类型,得到其Generic的类型
if (fc == null) { continue; }
if (fc instanceof ParameterizedType) // 3如果是泛型参数的类型
{
ParameterizedType pt = (ParameterizedType) fc;
Class genericClazz = (Class) pt.getActualTypeArguments()[0]; //4 得到泛型里的class类型对象。
System.out.println("=========" + genericClazz.getTypeName());
Type type=new ParameterizedTypeImpl(genericClazz);
Object obj = gson.fromJson(value, type);
System.out.println(obj.toString());
f.set(t,obj);//将对应的值写入到对应属性
}
} else {
//普通值的转换
Object obj = gson.fromJson(value, f.getType());
f.set(t,obj);
System.out.println(obj.toString());
}
}
}
}
return t;
}
//将对应实体中的实体进行转换为可用gson处理
public class ParameterizedTypeImpl implements ParameterizedType {
Class clazz;
public ParameterizedTypeImpl(Class clz) {
clazz = clz;
}
@Override
public Type[] getActualTypeArguments() {
return new Type[]{clazz};
}
@Override
public Type getRawType() {
return List.class;
}
@Override
public Type getOwnerType() {
return null;
}
}
以下为调用方法:
public static void main(String[] args) {
Gson gson = new Gson();
Map map = new HashMap();
BehaviorScore behaviorScore = new BehaviorScore();
behaviorScore.setBase_info_score(8767);
List<ReportAllContactStatsPerMonth> list = new ArrayList<>();
ReportAllContactStatsPerMonth reportAllContactStatsPerMonth = new ReportAllContactStatsPerMonth();
reportAllContactStatsPerMonth.setCall_count("343");
list.add(reportAllContactStatsPerMonth);
ReportAllContactStatsPerMonth reportAllContactStatsPerMonth2 = new ReportAllContactStatsPerMonth();
reportAllContactStatsPerMonth2.setCall_count_active_roam("56444");
list.add(reportAllContactStatsPerMonth2);
String behavior_score = gson.toJson(behaviorScore);
map.put("behavior_score", behavior_score);
String str = gson.toJson(list);
map.put("all_contact_stats_per_month", str);
try {
SjmhReportResultData sjmhReportResultDatatt = transformMapToSjmhReportResultData(map,
SjmhReportResultData.class);
System.out.println("pppppppppppppppppp" + sjmhReportResultDatatt);
} catch (Exception e) {
System.out.println("oooooooo" + e);
}
}