1. 程式人生 > >java反射實現物件轉JSON(貼上可用)

java反射實現物件轉JSON(貼上可用)



package test;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.lang.reflect.Field;
import java.util.Map;

public class JsonUtils {
 
 /**
  * @param obj
  * @return
  * @throws InstantiationException
  * @throws IllegalAccessException
  */
 public static String getJsonString(Object obj) throws InstantiationException, IllegalAccessException  {
  
  //如果傳入的物件為集合
  if (obj instanceof Collection) {
   
   //執行collectionTojson方法將集合型別轉為json格式
   return collectionTojson(obj);
   
  }
  
  //如果獲取的物件型別為一個Map集合
  else if (obj instanceof Map) {
   
   //執行mapTojson方法將Map型別轉為json格式
   return mapTojson(obj);
  
  }
  
  //如果獲取的物件型別為普通物件
  else{
   
   //執行classTojson方法將普通型別轉為json格式
   return classTojson(obj);
   
  }  
 }
   
 /**
  * @描述 將集合轉為json格式的字串
  * @param obj
  * @return
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  */
 private static String collectionTojson(Object obj) throws IllegalArgumentException, IllegalAccessException{
  
  //定義一個StringBuffer型別的字串
  StringBuffer buffer = new StringBuffer();
  buffer.append("[");
  
  Class<? extends Object> clazz = obj.getClass();
  
  //獲取類中所有的欄位
  Field[] declaredFields = clazz.getDeclaredFields();
  
  //設定可以獲得私有欄位的value
  Field.setAccessible(declaredFields, true);       
  
  //定義全域性變數
  boolean listf = false;
  boolean setf = false;
  Set<Object> set = null;
  List<Object> list = null;
  
  //遍歷獲取到的所有欄位
  for (Field field : declaredFields) {
   
   //getDeclaringClass()同getClasses(),但不侷限於public修飾,只要是目標類中宣告的內部類和介面均可
   
   String simpleName = clazz.getSimpleName();
   
    //判斷獲取到的型別
    if(simpleName.equals("ArrayList")||simpleName.equals("LinkedList")){
    list = (List<Object>) obj;
    listf=true;
    }
    if(simpleName.equals("HashSet")||simpleName.equals("TreeSet")){
     set = (Set<Object>) obj;
     setf=true;
    }
   
  }
  
  
  //如果獲取的物件型別為一個List集合
  if(listf == true){
   
   return listTojson(buffer, list).toString();
  
  }
  
  //如果獲取的物件型別為一個Set集合
  if(setf == true){
   
   buffer = setTojson(set, buffer);
  
  }
  
  buffer.append("]");
  
  return buffer.toString();
 }
 
 
 /**
  * 描述 將基本類轉為json格式
  * @param obj
  * @return
  */
 private static String classTojson(Object obj){
  
  //通過反射獲取到類
  Class<? extends Object> clazz = obj.getClass();
  
  //獲取類中所有的欄位
  Field[] fields = clazz.getDeclaredFields();
  
  StringBuffer buffer = new StringBuffer();
  buffer.append("[{");
  
  //設定setAccessible方法能獲取到類中的私有屬性和方法
  Field.setAccessible(fields, true);
  
  //遍歷所有的方法和屬性
  for (Field field : fields) {
   
   try {
    
    Object object = field.get(obj);
    
    //獲取到該屬性對應型別名稱
    String fieldName = field.getType().getSimpleName();
    
    //如果該屬性的值為空
    if(object == null){
     
     //根據型別判斷追加的值
     if(fieldName.equals("String"))
     {
      buffer.append("\""+field.getName()+"\":\"\",");
     }
     else if(fieldName.equals("Boolean")||fieldName.equals("Integer")||fieldName.equals("Double")||fieldName.equals("Float")||fieldName.equals("Long")){
      
      buffer.append("\""+field.getName()+"\":0,");
     }
    
     else{
      buffer.append("\""+field.getName()+"\":null,");
     }
     
    }
    else{
     
     //獲取到該屬性的值對應的類
     Class<? extends Object> fieldclass = object.getClass();
     String simpleName = fieldclass.getSimpleName();
    
    if(simpleName.equals("String")){
     
     buffer.append("\""+field.getName()+"\":\""+field.get(obj)+"\",");
    
    }
    else if(simpleName.equals("Boolean")||simpleName.equals("Integer")||simpleName.equals("Double")||simpleName.equals("Float")||simpleName.equals("Long")){
     
     buffer.append("\""+field.getName()+"\":"+field.get(obj)+",");
    
    }
    else if(simpleName.equals("Date")){
     
     Date date = (Date) object;
     SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
     String simdate = simpleDateFormat.format(date);
     buffer.append("\""+field.getName()+"\":\""+simdate+"\",");
    
    }
    else if(simpleName.equals("ArrayList")||simpleName.equals("LinkedList"))
    {
     //將獲取到的值強轉為list集合
     List<Object> list = (List<Object>) object;
     buffer.append("\""+field.getName()+"\":[");
     
     //執行listTojson方法將獲取到的list轉為json格式
     buffer = listTojson(buffer, list).append("]");
    }
    else if(simpleName.equals("HashSet")||simpleName.equals("TreeSet"))
    {
     //將獲取到的值強轉為set集合
     buffer.append("\""+field.getName()+"\":[");
     Set<Object> set = (Set<Object>) object;
     
     //執行setTojson方法將獲取到的set轉為json格式
     buffer = setTojson(set, buffer).append("]");
    
    }
    else if(simpleName.equals("HashMap")||simpleName.equals("HashTable"))
    {

     buffer.append("\""+field.getName()+"\":");
     
     //執行mapTojson方法將獲取到的map物件轉為json格式
     StringBuffer mapbuffer = new StringBuffer(mapTojson(object));
     mapbuffer.deleteCharAt(0);
     buffer.append(mapbuffer);
    }
    else{
      
      buffer = beanTojson(object,buffer).append(",");
     }
    }
    
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  
  }
  buffer = new StringBuffer(buffer.substring(0,buffer.length()-1));
  buffer.append("}]");
  
  return buffer.toString();
 }

 /**
  * 描述 將map集合轉為json格式
  * @param obj
  * @return
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  */
 private static String mapTojson(Object obj) throws IllegalArgumentException, IllegalAccessException{
  
  StringBuffer buffer = new StringBuffer();
  Class<? extends Object> clazz = obj.getClass();
  Field[] declaredFields = clazz.getDeclaredFields();
  Field.setAccessible(declaredFields, true);
  buffer.append("[");
  Map<Object,Object> map = (Map<Object, Object>) obj;
  
  //通過Map.entrySet使用iterator(迭代器)遍歷key和value
  Set<Entry<Object, Object>> set = map.entrySet(); 
        Iterator iterator = set.iterator(); 
        buffer.append("{");
       
        while (iterator.hasNext()){ 
         
         //使用Map.Entry接到通過迭代器迴圈出的set的值
            Map.Entry  mapentry = (Map.Entry) iterator.next(); 
            Object value = mapentry.getValue();
           
            //使用getKey()獲取map的鍵,getValue()獲取鍵對應的值
            String valuename = value.getClass().getSimpleName();
            if(valuename.equals("String")){
    
    buffer.append("\""+mapentry.getKey()+"\":\""+mapentry.getValue()+"\",");
   }
   else if(valuename.equals("Boolean")||valuename.equals("Integer")||valuename.equals("Double")||valuename.equals("Float")||valuename.equals("Long")){
    
    buffer.append("\""+mapentry.getKey()+"\":"+mapentry.getValue()+",");
   }
   else if(valuename.equals("Date")){
    Date date = (Date) value;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    String simdate = simpleDateFormat.format(date);
    buffer.append("\""+mapentry.getKey()+"\":\""+simdate+"\",");
   }else if(valuename.equals("ArrayList")||valuename.equals("LinkedList"))
   {
    List<Object> list = (List<Object>) value;
    buffer.append("\""+mapentry.getKey()+"\":[");
    buffer = listTojson(buffer, list).append("]");
   }
   else if(valuename.equals("HashSet")||valuename.equals("TreeSet"))
   {
    buffer.append("\""+mapentry.getKey()+"\":[");
    Set<Object> sets = (Set<Object>) value;
    buffer = setTojson(sets, buffer).append("]");
   }
   else if(valuename.equals("HashMap")||valuename.equals("HashTable"))
   {
    buffer.append("\""+mapentry.getKey()+"\":");
    StringBuffer mapbuffer = new StringBuffer(mapTojson(value));
    mapbuffer.deleteCharAt(0);
    buffer.append(mapbuffer);
   }
            else{
             buffer.append("\""+mapentry.getKey()+"\":");
             buffer.append("{");
             
             Class<? extends Object> class1 = value.getClass();
             Field[] fields = class1.getDeclaredFields();
             Field.setAccessible(fields, true);
             
             for (Field field : fields) {
              
              Object object = field.get(value);
              String fieldName = field.getType().getSimpleName();
              
     if(object == null){
      if(fieldName.equals("String"))
      {
       buffer.append("\""+field.getName()+"\":\"\",");
      }
     
      else{
       buffer.append("\""+field.getName()+"\":null,");
      }
      
     }
              else{
               
               Class<? extends Object> fieldclass = field.get(value).getClass();
               String simpleName = fieldclass.getSimpleName();
               if(simpleName.equals("String")){
       
       buffer.append("\""+field.getName()+"\":\""+field.get(value)+"\",");
      }
      else if(simpleName.equals("Boolean")||simpleName.equals("Integer")||simpleName.equals("Double")||simpleName.equals("Float")||simpleName.equals("Long")){
       
       buffer.append("\""+field.getName()+"\":"+field.get(value)+",");
      }
      else if(simpleName.equals("Date")){
       Date date = (Date) object;
       SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
       String simdate = simpleDateFormat.format(date);
       buffer.append("\""+field.getName()+"\":\""+simdate+"\",");
      }
      else if(simpleName.equals("ArrayList")||simpleName.equals("LinkedList")){
       
       List<Object> list = (List<Object>) object;
       buffer.append("\""+field.getName()+"\":[");
       StringBuffer append = listTojson(buffer, list).append("]");
       buffer.append(append);
      }
      else if(simpleName.equals("HashSet")||simpleName.equals("TreeSet")){
       
       buffer.append("\""+field.getName()+"\":[");
       Set<Object> sets = (Set<Object>) object;
       buffer = setTojson(sets, buffer).append("]");
      }
      else if(simpleName.equals("HashMap")||simpleName.equals("HashTable")){
       
       buffer.append("\""+field.getName()+"\":");
       StringBuffer mapbuffer = new StringBuffer(mapTojson(object));
       mapbuffer.deleteCharAt(0);
       buffer.append(mapbuffer);
      }
      else{
       buffer = beanTojson(object,buffer).append(",");
        
      }
              }
     
    }
             
             buffer =  new StringBuffer(""+buffer.substring(0,buffer.length()-1)+"");
             buffer.append("},");
            }
             
          }
       
         buffer =  new StringBuffer(""+buffer.substring(0,buffer.length()-1)+"");
   return buffer.toString()+"}]";
 }

 /**
  * @描述 將不是基本型別的欄位轉為json格式
  * @param obj
  * @param buffer
  * @return
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  */
 private static StringBuffer beanTojson(Object obj,StringBuffer buffer) throws IllegalArgumentException, IllegalAccessException{
  
  Class<? extends Object> clazz = obj.getClass();
  Field[] declaredFields = clazz.getDeclaredFields();
  Field.setAccessible(declaredFields, true);
  
  buffer.append("\""+clazz.getSimpleName()+"\":{");
  
  for (Field field : declaredFields) {
   
   Object object = field.get(obj);
   String fieldName = field.getType().getSimpleName();
   
   if(object == null){
    if(fieldName.equals("String"))
    {
     buffer.append("\""+field.getName()+"\":\"\",");
    }
   
    else{
     buffer.append("\""+field.getName()+"\":null,");
    }
    
   }
   else{
    
   Class<? extends Object> fieldclass = object.getClass();
   String simpleName = fieldclass.getSimpleName();
   
   if(simpleName.equals("String")){
    
    buffer.append("\""+field.getName()+"\":\""+field.get(obj)+"\",");
   }
   else if(simpleName.equals("Boolean")||simpleName.equals("Integer")||simpleName.equals("Double")||simpleName.equals("Float")||simpleName.equals("Long")){
    
    buffer.append("\""+field.getName()+"\":"+field.get(obj)+",");
   }
   else if(simpleName.equals("Date")){
    
    Date date = (Date) object;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    String simdate = simpleDateFormat.format(date);
    buffer.append("\""+field.getName()+"\":\""+simdate+"\",");
   }
   else if(simpleName.equals("ArrayList")||simpleName.equals("LinkedList")){
    
    List<Object> list = (List<Object>) object;
    buffer = listTojson(buffer, list);
   }
   else if(simpleName.equals("HashSet")||simpleName.equals("TreeSet")){
    
    Set<Object> set = (Set<Object>) object;
    buffer = setTojson(set, buffer);
   }
   else if(simpleName.equals("HashMap")||simpleName.equals("HashTable")){
    
    buffer.append("\""+field.getName()+"\":");
    StringBuffer mapbuffer = new StringBuffer(mapTojson(object));
    mapbuffer.deleteCharAt(0);
    buffer.append(mapbuffer);
   }
   else{
     buffer = beanTojson(object,buffer).append("}");
    }
   }
   
  }
  
  buffer =  new StringBuffer(""+buffer.substring(0,buffer.length()-1)+"");
  buffer.append("}");
  
  return buffer;
 }
 
 /**
  * @描述 將list陣列轉為json格式
  * @param buffer
  * @param list
  * @return
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  */
 private static StringBuffer listTojson(StringBuffer buffer,List list) throws IllegalArgumentException, IllegalAccessException{
  
 //遍歷傳過來的list陣列
 for (Object object : list) {
   
  //判斷遍歷出的值是否為空
  if (object == null) {
   buffer.append(","); 
  }
  else{
    
   Class<? extends Object> class1 = object.getClass();
   String simpleName = class1.getSimpleName();
    
   if(simpleName.equals("String")){
     
    buffer.append("\""+object.toString()+"\",");
   }
   else if(simpleName.equals("Boolean")||simpleName.equals("Integer")||simpleName.equals("Double")||simpleName.equals("Float")||simpleName.equals("Long")){
     
    buffer.append(""+object.toString()+",");
   }
   else if(simpleName.equals("Date")){
    Date date = (Date) object;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    String simdate = simpleDateFormat.format(date);
    buffer.append(""+simdate+",");
   }
   else{
     
    Class<? extends Object> class2 = object.getClass();
    Field[] fields = class2.getDeclaredFields();
    Field.setAccessible(fields, true);
    buffer.append("{");
    //遍歷物件中的所有欄位獲取欄位值和欄位名稱拼成json字串
    for (Field field : fields) {
      
     Object fieldobj = field.get(object);
     String fieldName = field.getType().getSimpleName();
      
     if(fieldobj == null){
       
      if(fieldName.equals("String"))
      {
       buffer.append("\""+field.getName()+"\":\"\",");
      }
      
      else{
       buffer.append("\""+field.getName()+"\":null,");
      }
       
     }
      
     else{
       
      String fsimpleName = fieldobj.getClass().getSimpleName();
       
      if(fsimpleName.equals("String")){
        
       buffer.append("\""+field.getName()+"\":\""+field.get(object)+"\",");
      }
      else if(fsimpleName.equals("Boolean")||fsimpleName.equals("Integer")||fsimpleName.equals("Double")||fsimpleName.equals("Float")||fsimpleName.equals("Long")){
        
       buffer.append("\""+field.getName()+"\":"+field.get(object)+",");
      }
      else if(fsimpleName.equals("Date")){
       
       Date date = (Date) object;
       SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
       String simdate = simpleDateFormat.format(date);
       buffer.append("\""+field.getName()+"\":"+simdate+",");
      }
      else{
       
       buffer = beanTojson(fieldobj, buffer).append(",");
      }
     }
      
    }
     
    buffer =  new StringBuffer(""+buffer.substring(0,buffer.length()-1)+"");
    buffer.append("},");
   }
   }
   
  }
  
  buffer =  new StringBuffer(""+buffer.substring(0,buffer.length()-1)+"");
  buffer.append("]");
  
  return buffer;
 }
 
 
 
 /**
  * @描述 將set陣列轉為json格式
  * @param set
  * @param buffer
  * @return
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  */
 private static StringBuffer setTojson(Set set,StringBuffer buffer) throws IllegalArgumentException, IllegalAccessException{
  
  for (Object object : set) {
   if (object == null) {
    buffer.append(""+"null"+","); 
   }
   else{
    
    Class<? extends Object> class1 = object.getClass();
    
    //判斷集合中的值是否為java基本型別
    String simpleName = class1.getSimpleName();
    if(simpleName.equals("String")){
     
     buffer.append("\""+object.toString()+"\",");
    }
    else if(simpleName.equals("Boolean")||simpleName.equals("Integer")||simpleName.equals("Double")||simpleName.equals("Float")||simpleName.equals("Long")){
     
     buffer.append(""+object.toString()+",");
    }
    else if(simpleName.equals("Date")){
     
     Date date = (Date) object;
     SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
     String simdate = simpleDateFormat.format(date);
     buffer.append(""+simdate+",");
    }
    else{
     
     Class<? extends Object> class2 = object.getClass();
     Field[] fields = class2.getDeclaredFields();
     Field.setAccessible(fields, true);
     buffer.append("{");
     
     //遍歷物件中的所有欄位獲取欄位值和欄位名稱拼成json字串
     for (Field field : fields) {
      
      Object fieldobj = field.get(object);
      String fieldName = field.getType().getSimpleName();
      
      if(object == null){
       if(fieldName.equals("String"))
       {
        buffer.append("\""+field.getName()+"\":\"\",");
       }
      
       else{
        buffer.append("\""+field.getName()+"\":null,");
       }
       
      }
      else{
       
       String fsimpleName = fieldobj.getClass().getSimpleName();
       if(fsimpleName.equals("String")){
        
        buffer.append("\""+field.getName()+"\":\""+field.get(object)+"\",");
       }
       else if(fsimpleName.equals("Boolean")||fsimpleName.equals("Integer")||fsimpleName.equals("Double")||fsimpleName.equals("Float")||fsimpleName.equals("Long")){
        
        buffer.append("\""+field.getName()+"\":"+field.get(object)+",");
       }
       else if(fsimpleName.equals("Date")){
        
        Date date = (Date) object;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String simdate = simpleDateFormat.format(date);
        buffer.append("\""+field.getName()+"\":"+simdate+",");
       }
       else{
        
        buffer = beanTojson(fieldobj, buffer).append(",");
       }
      } 
     }
     
     buffer =  new StringBuffer(""+buffer.substring(0,buffer.length()-1)+"");
     buffer.append("},");
    }
   }
  }
  
  buffer =  new StringBuffer(""+buffer.substring(0,buffer.length()-1)+"");
  return buffer;
 }
      
}