后台到前台的Json传递,数据库直接取出List类型 转为Json,虽然网上有个Json-lib的包…… 但是依赖的其他基础包太多了…… 不想找了……
/*Java反射函数机制 List转换Json*/
public String getJsonData(List list) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException{
String jsonTemp="{results:[";
for(int i=0;i<list.size();i++){
jsonTemp=jsonTemp+"{";
Field[] field=list.get(i).getClass().getDeclaredFields();//获取参数数组
for (int j=0;j<field.length;j++) {
Method metd=list.get(i).getClass().getMethod("get"+field[j].getName().substring(0,1).toUpperCase()+field[j].getName().substring(1),null);// 根据字段名找到对应的get方法,null表示查找的方法无参数
jsonTemp=jsonTemp+field[j].getName()+":'"+metd.invoke(list.get(i),null)+"'";//调用找到的函数
if(j!=field.length-1){
jsonTemp=jsonTemp+",";
}
}
if(i!=list.size()-1){
jsonTemp=jsonTemp+"},";
}
else{
jsonTemp=jsonTemp+"}";
}
}
jsonTemp=jsonTemp+"]}";
return jsonTemp;
}
这样子输出的json就变成了比如
{results:[
{id:'0',name:'白鹤',broadband:'123',iptv:'100',c:'543',cw:'23'},
{id:'1',name:'重固',broadband:'200',iptv:'134',c:'265',cw:'21'},
{id:'2',name:'大盈',broadband:'14',iptv:'12',c:'2',cw:'5'},
{id:'3',name:'香花',broadband:'3',iptv:'2',c:'1',cw:'4'},
{id:'4',name:'赵屯',broadband:'43',iptv:'23',c:'84',cw:'2'},
{id:'5',name:'赵巷',broadband:'153',iptv:'251',c:'36',cw:'82'}
]}
这个样子…… 可以给Extjs直接传了……