问题描述:将json数组不能直接转换成list这种形式,只能转换成list,这个给我们编程带来一些问题,又要多种一次转换.为了解决这个问题,我们通过Java的反射机制解决了这一问题. 1.首先定义一个自定义的注解接口
@Retention(RetentionPolicy.RUNTIME) public @interface ItemType { /** * 子类型的类名 * * @return */ Class<?> classType(); }然后再需要转换成List的地方标记,如下:
class School { //标记list容器里面的对象类型 @ItemType(classType=Student.class) List<Student> studnets; } class Student { }下面实现解析代码
/** * 将json对象转换成bean * * @param jsonObject * @param beanClass * @return */ public static <T> T toBean(JSONObject jsonObject, Class<T> cls) { T obj = null; try { if (jsonObject != null) { Field fields[] = cls.getDeclaredFields(); obj = cls.newInstance(); for (Field field : fields) { field.setAccessible(true); if (jsonObject.has(field.getName())) { field.setAccessible(true); if (field.getType() == String.class) { field.set(obj, jsonObject.getString(field.getName())); } else if (field.getType() == Boolean.class) { field.set(obj, jsonObject.getBoolean(field.getName())); } else if (field.getType() == int.class) { field.set(obj, jsonObject.getInt(field.getName())); } else if (field.getType() == Integer.class) { field.set(obj, jsonObject.getInt(field.getName())); } else if (field.getType() == Long.class) { field.set(obj, jsonObject.getLong(field.getName())); } else if (field.getType() == Double.class) { field.set(obj, jsonObject.getDouble(field.getName())); } else if (field.getType() == List.class) { JSONArray jsonArray = jsonObject.optJSONArray(field .getName()); //关键点,获取到注解的信息,然后通过反射获取到类型 ItemType itemType = field .getAnnotation(ItemType.class); if (itemType != null && jsonArray != null) { Class<?> item = itemType.classType(); List itemlist = new ArrayList(); for (int i = 0; i < jsonArray.size(); i++) { JSONObject object_child = jsonArray .getJSONObject(i); itemlist.add(toBean(object_child, item)); } field.set(obj, itemlist); } else { throw new Exception(field.getType().toString() + " mush be had itemType"); } } else { field.set(obj, jsonObject.get(field.getName())); } } } } } catch (Exception e) { e.printStackTrace(); } return obj; }