利用反射将bean转化为JsonString输出


1.
    我们这里的目标是,将一个bean
public class UserBean{

    private String name ;
    private String sex ;
    private Integer age ;
    private Date birth ;
    private Dept dept;

   ...省略get set 方法未写出来
}

public class  Dept{

    private String deptName ;
    private Integer deptNo;
    private String deptManager;

    ...省略get set 方法未写出来
}
    转化为JsonString 
{"name":"小明","sex":"男","age":22,"birth":2010-10-01,"dept":{" deptName":"研发部"," deptNo":1001," deptManager":"小刚"}}

2.
定义规则:
       1). 忽略值为null 的键值对;
       2).支持一个bean 中嵌套另一个bean ;
        
思路:
        1).利用反射能获取bean 中的字段属性名称;
        2).需判断字段类型是基础类型还是对象类型;
        3).按JSON的规则拼接。

3.

实现:
package hlm.com.json ;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

import org.apache.commons.logging.Log ;
import org.apache.commons.logging.LogFactory ;
import org.springframework.util.StringUtils;

public class JSONUtils {
            
    private static final Log logger = LogFactory.getLog(JSONUtils.class);
    
    /**
     * 返回  {"deptName":"研发部","deptNo":1001,"deptManager":"小刚"}   样子的字符串
     * @param obj
     * @return
     */
    public static String transferBean2JsonString(Object obj){
        //获取Class 对象
        Class clzz = obj.getClass();
        //获取属性数组
        Field[] fieldArray = clzz.getDeclaredFields();
        //容器
        StringBuffer sb = new StringBuffer();
        //循环
        for(Field field : fieldArray){
            String name = field.getName();
            //System.out.println(name);
            logger.info("name :"+name);
            Type type = field.getGenericType();
            //System.out.println(type);
            logger.info("type :"+type);
            try {
                Method method = clzz.getMethod("get"+name.substring(0, 1).toUpperCase()+name.substring(1), null);
                Object returnValue = method.invoke(obj, null);
                if(returnValue != null){
                    if(isBaseType(type)){                        
                        sb.append(buildString(addStringMark(name,String.class) , addStringMark(returnValue,type)));
                        logger.info("returnValue :"+returnValue);
                    }else{
                        String returnStr =transferBean2JsonString(returnValue);
                        sb.append(buildString(addStringMark(name,String.class) ,addStringMark(returnStr,type)));
                        logger.info("returnValue :"+returnStr);
                    }
                }
            } catch (NoSuchMethodException e) {

                e.printStackTrace();
            } catch (SecurityException e) {

                e.printStackTrace();
            } catch (IllegalAccessException e) {

                e.printStackTrace();
            } catch (IllegalArgumentException e) {

                e.printStackTrace();
            } catch (InvocationTargetException e) {

                e.printStackTrace();
            }                            
        }//for end
        
        return buildObjectString(sb);        
    }
    
    /**
     * 判断基础类型
     * @param type
     * @return
     */
    public static boolean isBaseType(Type type){
        
        if(type == null) return false ;
        if(type.getTypeName().indexOf("String")>=0 ){
            return true ;
        }
        else if(type.getTypeName().indexOf("Integer")>=0){
            return true ;
        }
        else if(type.getTypeName().indexOf("Long")>=0){
            return true ;
        }
        else if(type.getTypeName().indexOf("Double")>=0){
            return true ;
        }
        else if(type.getTypeName().indexOf("Float")>=0){
            return true ;
        }
        else if(type.getTypeName().indexOf("Date")>=0){
            return true ;
        }
        else if(type.getTypeName().indexOf("int")>=0){
            return true ;
        }
        else if(type.getTypeName().indexOf("long")>=0){
            return true ;
        }
        else if(type.getTypeName().indexOf("double")>=0){
            return true ;
        }
        else if(type.getTypeName().indexOf("float")>=0){
            return true ;
        }
        return false;
    }
    
    public static String  buildString(Object name ,Object returnValue){
        
        if(returnValue==null || StringUtils.isEmpty(name)){
            return null;
        }
        return name+":"+returnValue.toString()+"," ;
    }
    
    /**
     * 为某个对象加上大括号
     * @param sb
     * @return
     */
    public static String buildObjectString(StringBuffer sb){
        if(sb == null || StringUtils.isEmpty(sb.toString())) return "";
        String returnStr = sb.toString();
        returnStr = returnStr.substring(0, returnStr.length()-1);
        return "{"+returnStr+"}";
        
    }
    
    /**
     * 为String 类型的值为双引号
     * @return
     */
    public static Object addStringMark(Object value,Type type){
        if(value!=null && type.getTypeName().indexOf("String")>=0){
            return "\""+value + "\"" ;
        }
        return value;
    }
    
}


package hlm.com.json;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.hibernate.validator.internal.util.StringHelper ;
import com.alibaba.fastjson.JSONObject;
public class Test {
      public static void main(String[] args ) {
           Dept dept = new Dept() ;
            dept .setDeptNo(1001);
            dept .setDeptName( "研发部" );
            dept .setDeptManager( "刘德华" );
           
           User user = new User();
            user .setAge(22);
            DateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" ); 
          Date birth = null ;
            try {
                 birth = dateFormat .parse( "2010-10-01" );
           } catch (ParseException e ) {
                 e .printStackTrace();
           } 
            user .setBirth( birth );
            user .setSex( "男" );
            user .setDept( dept );
            user .setName( "小明" );
           
           String userJSONString = JSONUtils. transferBean2JsonString ( user );
           String Str = JSONObject. toJSONString ( user );
           System. out .println( userJSONString );
           System. out .println( Str );
           
     }
}

结果
{"name":"小明","sex":"男","age":22,"birth":Fri Oct 01 00:00:00 CST 2010,"dept":{"deptName":"研发部","deptNo":1001,"deptManager":"刘德华"}}
{"age":22,"birth":1285862400000,"dept":{"deptManager":"刘德华","deptName":"研发部","deptNo":1001},"name":"小明","sex":"男"}

从结果中可以看出,与使用别人工具jar 包中的方法得到的结果几乎一样,只不过别人的日期是经过处理了。

4.

总结:在结果处理这块可以再深入到某些类如日期这种的灵活处理,另处还可以添加数组和list类型的处理方法。判断类型这一块地方可能方法不是很好,应该有别的方法来进行类型判断的。


---------------

后续有作修改,为了不让文章篇幅过长,只好另写一篇了。

利用反射将bean转化为JsonString输出 (改进版)

你可能感兴趣的:(Java)