从JSONObject中解析数据,并赋给给定的对象
public static Object parseBean(JSONObject jsonObject, Object obj) { if (jsonObject == null || obj == null) { return null; } Class clazz = obj.getClass(); Iterator it = jsonObject.keys(); Field field = null; String key = null; try { while (it.hasNext()) { key = it.next().toString(); // 获得对应的属性 field = clazz.getDeclaredField(key); // 获得属性对应的值 Object val = jsonObject.get(key); // 暂不考虑Date类型 if (field.getType() == Integer.TYPE) { val = Integer.parseInt(val.toString()); } else if(field.getType() == Long.TYPE||field.getType() == Long.class) { val = Long.parseLong(val.toString()); } else if (field.getType() == Date.class) { if (field.isAnnotationPresent(DateTimeFormat.class)) { String pattern = field.getAnnotation(DateTimeFormat.class).pattern(); val = DateUtil.parse(val.toString(), pattern); } else { val = DateUtil.parseDate(val.toString()); } }else if(field.getType() == BigDecimal.class) { if (StringUtils.hasText(val.toString())) { val = new BigDecimal(val.toString()); }else{ val = null; } } // 赋值 field.setAccessible(true); field.set(obj, val); } } catch (Exception e) { e.printStackTrace(); return null; } return obj; }