import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
?
import org.apache.commons.beanutils.BeanUtils;
?
public class AjaxUtil {
??? /**
???? * 將list結構轉變成js的array結構,要求list中包含的是model
???? * 例如:[{id:'1001',name:'test1'},{id:'1002',name:'test2'},{id:'1003',name:'test3'}]
???? *
???? * @param list
???? *??????????? List結構
???? * @return js的array結構
???? *
???? * @throws IllegalAccessException
???? * @throws InvocationTargetException
???? * @throws NoSuchMethodException
???? */
??? public static String list2StrArray(List list) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
??????? StringBuffer strMap = new StringBuffer();
?
??????? strMap.append("[");
??????? int listSize = list.size();
??????? for (int i = 0; i < listSize; i++) {
??????????? Object obj = list.get(i);
?
??????????? if (i != listSize - 1)
??
?????????????strMap.append(model2StrMap(obj)).append(",");
??????????? else
??????????????? strMap.append(model2StrMap(obj));
??????? }
??????? strMap.append("]");
?
??????? return strMap.toString();
??? }
?
??? /**
???? * 將model的結構轉變成js的map結構
???? * 例如:{id:'1001',name:'test'}
???? *
???? * @param obj
???? *??????????? 任一對象
???? * @return js的map結構
???? *
???? * @throws IllegalAccessException
???? * @throws InvocationTargetException
???? * @throws NoSuchMethodException
???? */
??? public static String model2StrMap(Object obj) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
??????? StringBuffer strMap = new StringBuffer();
?
??????? // 獲得model的屬性字段
??????? Class clazz = obj.getClass();
??????? Field[] fields = clazz.getDeclaredFields();
?
??????? // 取出mode的屬性值
??????? strMap.append("{");
??????? for (int i = 0; i < fields.length; i++) {
??????????? String fieldName = fields[i].getName();
??????????? String fieldValue = BeanUtils.getProperty(obj, fieldName);
?
??????????? if (i != fields.length - 1)
??????????????? strMap.append(fieldName + ":'" + fieldValue + "',");
??????????? else
??????????????? strMap.append(fieldName + ":'" + fieldValue + "'");
??????? }
??????? strMap.append("}");
?
??????? return strMap.toString();
??? }
?
}
|