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();
}
}
|