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

    利用反射将bean转化为JsonString输出  这个例子中,有好几种类型没有考虑到,特别是StringBuilder 、泛型等。泛型我还没想好如何处理,先添加StringBuilder及其他的类型,并调整一下代码方式。泛型想好如何处理了再更新此篇。
package hlm.com.json;
import java.io.Serializable;
import java.util.Date;
public class User< T > implements Serializable  {
      private static final long serialVersionUID = -6562205181367715396L;
      private String name ;
    private String sex ;
    private Integer age ;
    private Date birth ;
    private Dept dept ;
    private boolean isManager ;
    private T type ;
    private StringBuilder stringBuilder ;
   
      public String getName() {
            return name ;
     }
      public void setName(String name ) {
            this . name = name ;
     }
      public String getSex() {
            return sex ;
     }
      public void setSex(String sex ) {
            this . sex = sex ;
     }
      public Integer getAge() {
            return age ;
     }
      public void setAge(Integer age ) {
            this . age = age ;
     }
      public Date getBirth() {
            return birth ;
     }
      public void setBirth(Date birth ) {
            this . birth = birth ;
     }
      public Dept getDept() {
            return dept ;
     }
      public void setDept(Dept dept ) {
            this . dept = dept ;
     }
      public boolean getIsManager() {
            return isManager ;
     }
      public void setIsManager( boolean isManager ) {
            this . isManager = isManager ;
     }
      public T getType() {
            return type ;
     }
      public void setType( T type ) {
            this . type = type ;
     }
      public StringBuilder getStringBuilder() {
            return stringBuilder ;
     }
      public void setStringBuilder(StringBuilder stringBuilder ) {
            this . stringBuilder = stringBuilder ;
     }
   
   
}

package hlm.com.json;
import java.math.BigDecimal;
public class Dept {
      private String deptName ;
    private Integer deptNo ;
    private Object deptManager ;
    private byte num ;
    private BigDecimal bigDecimal ;
      public String getDeptName() {
            return deptName ;
     }
      public void setDeptName(String deptName ) {
            this . deptName = deptName ;
     }
      public Integer getDeptNo() {
            return deptNo ;
     }
      public void setDeptNo(Integer deptNo ) {
            this . deptNo = deptNo ;
     }
      public Object getDeptManager() {
            return deptManager ;
     }
      public void setDeptManager(Object deptManager ) {
            this . deptManager = deptManager ;
     }
      public byte getNum() {
            return num ;
     }
      public void setNum( byte num ) {
            this . num = num ;
     }
      public BigDecimal getBigDecimal() {
            return bigDecimal ;
     }
      public void setBigDecimal(BigDecimal bigDecimal ) {
            this . bigDecimal = bigDecimal ;
     }
     
   
}

package hlm.com.json;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType ;
import java.lang.reflect.Type;
import java.util.ArrayList;
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 );
      private static   ArrayList baseType = new ArrayList();
      static {
            baseType .add( "java.lang.String" );          
            baseType .add( "java.util.Date" );
            baseType .add( "java.sql.Date" );
            baseType .add( "java.lang.Integer" );
            baseType .add( "java.lang.Long" );
            baseType .add( "java.lang.Byte" );
            baseType .add( "java.lang.Double" );
            baseType .add( "java.lang.Foalt" );
            baseType .add( "java.lang.Boolean" );
            baseType .add( "java.math.BigDecimal" );
            baseType .add( "boolean" );
            baseType .add( "byte" );
            baseType .add( "int" );
            baseType .add( "long" );
            baseType .add( "float" );
            baseType .add( "double" );
            baseType .add( "java.lang.Object" );
            baseType .add( "java.lang.String" );
            baseType .add( "java.lang.StringBuilder" );
     }
      /**
      * 返回  {"deptName":"研发部","deptNo":1001,"deptManager":"小刚"}   样子的字符串
      * @param obj
      * @return
      */
      public static String transferBean2JsonString(Object obj ){
            //获取Class 对象
           Class extends Object> 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 ) {
                      continue ;
                } 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 ( baseType .contains( type .getTypeName())){
                 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( "StringBuilder" )>=0){
                 return "\"" + value .toString() + "\"" ;
           }
            else if ( value != null && type .getTypeName().indexOf( "String" )>=0){
                 return "\"" + value + "\"" ;
           }
           
            return value ;
     }
     
     
     
}

package hlm.com.json;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
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( "刘德华" );
            dept .setNum(( byte ) 0);
            dept .setBigDecimal( new BigDecimal(1000000));
           
            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( "小明" );
            user .setAge(20);
            user .setIsManager( false );
            user .setType( "type" ) ;
            user .setStringBuilder( new StringBuilder( "stringBuilder" ));
           
           String userJSONString = JSONUtils. transferBean2JsonString ( user );
            //找了一个别人写的方法来对比
           String Str = JSONObject. toJSONString ( user );
           System. out .println( userJSONString );
           System. out .println( Str );
           
     }
}

结果:
22:57:13.858 [main] INFO hlm.com.json.JSONUtils - name :serialVersionUID
22:57:13.862 [main] INFO hlm.com.json.JSONUtils - type :long
22:57:13.862 [main] INFO hlm.com.json.JSONUtils - name :name
22:57:13.862 [main] INFO hlm.com.json.JSONUtils - type :class java.lang.String
22:57:13.864 [main] INFO hlm.com.json.JSONUtils - returnValue :小明
22:57:13.864 [main] INFO hlm.com.json.JSONUtils - name :sex
22:57:13.864 [main] INFO hlm.com.json.JSONUtils - type :class java.lang.String
22:57:13.864 [main] INFO hlm.com.json.JSONUtils - returnValue :男
22:57:13.864 [main] INFO hlm.com.json.JSONUtils - name :age
22:57:13.864 [main] INFO hlm.com.json.JSONUtils - type :class java.lang.Integer
22:57:13.864 [main] INFO hlm.com.json.JSONUtils - returnValue :20
22:57:13.864 [main] INFO hlm.com.json.JSONUtils - name :birth
22:57:13.864 [main] INFO hlm.com.json.JSONUtils - type :class java.util.Date
22:57:13.866 [main] INFO hlm.com.json.JSONUtils - returnValue :Fri Oct 01 00:00:00 CST 2010
22:57:13.866 [main] INFO hlm.com.json.JSONUtils - name :dept
22:57:13.866 [main] INFO hlm.com.json.JSONUtils - type :class hlm.com.json.Dept
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - name :deptName
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - type :class java.lang.String
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - returnValue :研发部
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - name :deptNo
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - type :class java.lang.Integer
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - returnValue :1001
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - name :deptManager
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - type :class java.lang.Object
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - returnValue :刘德华
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - name :num
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - type :byte
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - returnValue :0
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - name :bigDecimal
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - type :class java.math.BigDecimal
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - returnValue :1000000
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - returnValue :{"deptName":"研发部","deptNo":1001,"deptManager":刘德华,"num":0,"bigDecimal":1000000}
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - name :isManager
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - type :boolean
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - returnValue :false
22:57:13.867 [main] INFO hlm.com.json.JSONUtils - name :type
22:57:13.871 [main] INFO hlm.com.json.JSONUtils - type :T
22:57:13.872 [main] INFO hlm.com.json.JSONUtils - name :value
22:57:13.872 [main] INFO hlm.com.json.JSONUtils - type :class [C
22:57:13.872 [main] INFO hlm.com.json.JSONUtils - name :hash
22:57:13.872 [main] INFO hlm.com.json.JSONUtils - type :int
22:57:13.873 [main] INFO hlm.com.json.JSONUtils - name :serialVersionUID
22:57:13.873 [main] INFO hlm.com.json.JSONUtils - type :long
22:57:13.873 [main] INFO hlm.com.json.JSONUtils - name :serialPersistentFields
22:57:13.873 [main] INFO hlm.com.json.JSONUtils - type :class [Ljava.io.ObjectStreamField;
22:57:13.873 [main] INFO hlm.com.json.JSONUtils - name :CASE_INSENSITIVE_ORDER
22:57:13.873 [main] INFO hlm.com.json.JSONUtils - type :java.util.Comparator
22:57:13.873 [main] INFO hlm.com.json.JSONUtils - returnValue :
22:57:13.873 [main] INFO hlm.com.json.JSONUtils - name :stringBuilder
22:57:13.873 [main] INFO hlm.com.json.JSONUtils - type :class java.lang.StringBuilder
22:57:13.874 [main] INFO hlm.com.json.JSONUtils - returnValue :stringBuilder
{"name":"小明","sex":"男","age":20,"birth":Fri Oct 01 00:00:00 CST 2010,"dept":{"deptName":"研发部","deptNo":1001,"deptManager":刘德华,"num":0,"bigDecimal":1000000},"isManager":false,"type":,"stringBuilder":"stringBuilder"}
{"age":20,"birth":1285862400000,"dept":{"bigDecimal":1000000,"deptManager":"刘德华","deptName":"研发部","deptNo":1001,"num":0},"isManager":false,"name":"小明","sex":"男","stringBuilder":"stringBuilder","type":"type"}

1.泛型未处理,所以空掉了;
2.当一个属性没有set 方法时表示默认该字段是不能取到值的,所以在异常处直接进入下一轮了。

你可能感兴趣的:(Java)