`
shihuan830619
  • 浏览: 574096 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Java反射函数机制实现List转换Json

    博客分类:
  • J2SE
阅读更多
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.math.BigDecimal;

import org.apache.commons.lang.StringUtils;

//import org.json.JSONArray;
//import org.json.JSONObject;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JSONArray;

import com.zznode.inms.broadbank.admin.dto.TbPingtaskResultDto;

public class ListDtoToJson {
	
	/**Java反射函数机制 List转换Json,返回[{"name":"value"},{"shihuan":"yushibo"},{...}]格式的String字符串*/ 
    public static String getJsonData(List list) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
//    	String jsonTemp = "{results:[";
    	String jsonTemp = "[";
    	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)+"'";  //调用找到的函数 
    			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+"]}";
    	jsonTemp = jsonTemp+"]";
    	return jsonTemp;
    }

    /**Java反射函数机制 List转换Json,返回[{"name":"value"};{"shihuan":"yushibo"};{...}]格式的String字符串*/ 
    public static String getJsonDataBaseList(List list) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
//    	String jsonTemp = "{results:[";
    	String jsonTemp = "";
    	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)+"'";  //调用找到的函数 
//    			jsonTemp = jsonTemp+"\""+field[j].getName()+"\":\""+metd.invoke(list.get(i),null)+"\"";  //调用找到的函数

    			if("java.math.BigDecimal".equals(field[j].getType().getName()) && metd.invoke(list.get(i), null).toString().indexOf(".") != -1){
    					double doubleTypeData = getDoubleTypeData(metd.invoke(list.get(i), null).toString());
        				jsonTemp = jsonTemp+field[j].getName()+":"+doubleTypeData;  //调用找到的函数
    			}else if("java.lang.String".equals(field[j].getType().getName())){
    				if(!"".equals(nullToString(metd.invoke(list.get(i), null))))
    					jsonTemp = jsonTemp+field[j].getName()+":'"+metd.invoke(list.get(i), null)+"'";  //调用找到的函数
    			}else{
    				if(!"".equals(nullToString(metd.invoke(list.get(i), null))))
    					jsonTemp = jsonTemp+field[j].getName()+":"+metd.invoke(list.get(i), null);  //调用找到的函数
    			}
    			
    			if(j != field.length-1){
    				if(!"".equals(nullToString(metd.invoke(list.get(i), null))))
    					jsonTemp = jsonTemp+",";
    			}
    		}
    		if(i != list.size()-1){
    			jsonTemp = jsonTemp+"};";
    		}else{
    			jsonTemp = jsonTemp+"}";
    		}
    	}
//    	jsonTemp = jsonTemp+"]}";
    	jsonTemp = jsonTemp+"";
    	return jsonTemp;
    }
    
    /**将Json格式的String字符串拼装成List对象
     * @throws InvocationTargetException 
     * @throws NoSuchMethodException 
     * @throws IllegalAccessException */
    public static List getListJson(List list) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    	List jsonlist = new ArrayList();
    	String jsonStrBaseList = getJsonDataBaseList(list);
    	String[] jsonStr = jsonStrBaseList.split(";");
    	int len = jsonStr.length;
    	for(int i=0; i<len; i++){
    		jsonlist.add((Object)jsonStr[i]);
    	}
    	return jsonlist;
    }
    
    public static double getDoubleTypeData(String param) {
    	DecimalFormat df = new DecimalFormat("#.00");  //.后面0的个数为小数位数
		BigDecimal bdStr = new BigDecimal(param);
		bdStr = bdStr.setScale(2, BigDecimal.ROUND_UP);
		double bdStrz = bdStr.doubleValue();
		String dfStr = df.format(bdStrz);
		return bdStrz;
    }
    
    public static String nullToString(Object val) {
		if (val == null) {
			val = "";
		}
		return val.toString();
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics