package util;
import org.json.JSONObject;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
public class JsonToPo {
//一个静态类,将json对象,转化为java
public static Object jsonToObject(JSONObject jsonObject, Class c) throws IllegalAccessException, InstantiationException {
Object obj=c.newInstance();
Iterator it=jsonObject.keySet().iterator();
Field[] fields=c.getDeclaredFields();
while(it.hasNext()) {
String key = (String) it.next();
//判断字段
for (Field field : fields) {
if (field.getName().equals(key)) {
// System.out.println("获取到的所有字段"+key);
useSetter(c, field, jsonObject,obj);
break;
}
}
}
return obj;
}
//调用该类的setter方法
private static void useSetter(Class c, Field field,JSONObject jsonObject,Object obj){
//获取字段类型以及字段名称
Class fieldType=field.getType();
String fieldName=field.getName();
String methodName=toMethodName(fieldName);
//System.out.println(methodName+"类型"+fieldType);
//调用方法
try {
Method method=c.getMethod(methodName,fieldType);
// System.out.println(method);
method.invoke(obj,jsonObject.get(fieldName));
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//将fieldName转化为方法名称
private static String toMethodName(String name){
String methodName="set"+name.substring(0,1).toUpperCase()+name.substring(1);
return methodName;
}
}