android 反射封装Json

来源:互联网 发布:不用网络的手机电视 编辑:程序博客网 时间:2024/05/19 22:48
// 需要传一个json 对象 和一个 类
public static List<Object> ClassTest2(JSONArray json,Class cg){
List<Object> list = new ArrayList<Object>();
 try {
Field[] fs= cg.getDeclaredFields();
AccessibleObject.setAccessible(fs, true);
for (int i = 0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
Object obj = cg.newInstance(); 
for (int j = 0; j < fs.length; j++) {
Field f = fs[j];
Object value = jsonObject.get(f.getName().toLowerCase());
f.set(obj, value);
}
list.add(obj); 
}
 
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

return list;
}
原创粉丝点击