@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface QueryParam {} /<strong> * JSON 拆解、装配工具 */ public class JsonUtil { private static final Log LOG = LogFactory.getLog(JsonUtil.class); private static final DateFormat dateFormat = DateFormat .getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
/</strong> * 将JSON字符串装配成对象 * * @param jsonString * JSON字符串 * @param object * 被装配的目标对象 */ public static void assemble(String jsonString, Object object) { try { JSONObject json = new JSONObject(jsonString); Field fields[] = object.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); QueryParam param = field.getAnnotation(QueryParam.class); if (param == null) { continue; } if (JSONObject.NULL == json.get(field.getName())) { field.set(object, null); continue; } Type type = field.getType(); //虽然我知道可以用其它形式书写下面这些,不过就这么几个,将就一下吧 if (type == Integer.class) { field.set(object, json.getInt(field.getName())); } else if (type == Double.class) { field.set(object, json.getDouble(field.getName())); } else if (type == Long.class) { field.set(object, json.getLong(field.getName())); } else if (type == Boolean.class) { field.set(object, json.getBoolean(field.getName())); } else if (type == Date.class) { String dateString = json.getString(field.getName()); field.set(object, dateFormat.parse(dateString)); } else { field.set(object, json.getString(field.getName())); } } } catch (JSONException e) { LOG.debug(e); } catch (IllegalArgumentException e) { LOG.debug(e); } catch (IllegalAccessException e) { LOG.debug(e); } catch (ParseException e) { LOG.debug(e); } }
/<strong> * 将对象拆解成JSON字符串 * * @param object * 被拆解的对象 * @return JSON字符串 */ public static String disassemble(Object object) { try { Field fields[] = object.getClass().getDeclaredFields(); JSONStringer json = new JSONStringer(); JSONWriter writer = json.object(); for (Field field : fields) { field.setAccessible(true); QueryParam param = field.getAnnotation(QueryParam.class); if (param == null) { continue; } Type type = field.getType(); if (type == Date.class) { Date date = (Date) field.get(object); writer.key(field.getName()).value(dateFormat.format(date)); } else { writer.key(field.getName()).value(field.get(object)); } } writer.endObject(); return writer.toString(); } catch (JSONException e) { LOG.debug(e); } catch (IllegalArgumentException e) { LOG.debug(e); } catch (IllegalAccessException e) { LOG.debug(e); } return null; } }
|