您的位置:首页 > 移动开发 > Objective-C

通过java内省,把json对象转为Object

2012-09-10 22:57 369 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: