package reflect;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* 自省方式
* @author Jeremy
*
*/
public class JsonUtils {
/**
* JSONObject 转自定义对象
* @param json
* @param beanClass
* @return
*/
public static <T> T jsonToBean(JSONObject json, Class<T> beanClass) {
T retObj = null;
JSONArray jsonPropertyNames = json.names();
List<String> propertyNames = getPropertyNames(beanClass);
try {
// 实例化
retObj = beanClass.newInstance();
for (int i = 0; i < jsonPropertyNames.length(); i++) {
String propName = jsonPropertyNames.getString(i);
Object value = json.get(propName);
// 如果类中有该json对象的属性,才获取
if (propertyNames.contains(propName)) {
PropertyDescriptor pd = new PropertyDescriptor(propName, beanClass);
Method m = pd.getWriteMethod();
if (m != null) {
m.invoke(retObj, value);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return retObj;
}
public static List<String> getPropertyNames(Class<?> clazz) {
List<String> propNames = new ArrayList<String>();
try {
BeanInfo bi = Introspector.getBeanInfo(clazz);
PropertyDescriptor[] pd = bi.getPropertyDescriptors();
for ( int i=0;i<pd.length;i++){
PropertyDescriptor p = pd[i];
String propName = p.getName();
propNames.add(propName);
}
} catch (Exception e) {
e.printStackTrace();
}
return propNames;
}
}
通过java内省,把json对象转为Object
最新推荐文章于 2024-07-01 02:07:36 发布