tinguo002

           

          JAVA反射機制,把JavaBean屬性轉成字符串

          package com.jetsum.util;

          import java.io.StringReader;
          import java.lang.reflect.Field;
          import java.util.ArrayList;
          import java.util.List;
          import java.util.Map;
          import java.util.Set;

          import antlr.RecognitionException;
          import antlr.TokenStreamException;

          import com.sdicons.json.mapper.JSONMapper;
          import com.sdicons.json.mapper.MapperException;
          import com.sdicons.json.model.JSONArray;
          import com.sdicons.json.model.JSONValue;
          import com.sdicons.json.parser.JSONParser;

          public class JsonUtil {

              
          /**
               * JAVA對象轉換成JSON字符串
               * 
          @param obj
               * 
          @return
               * 
          @throws MapperException
               
          */
              
              
          public static String objectToJsonStr(Object obj) throws MapperException{
                  JSONValue jsonValue 
          = JSONMapper.toJSON(obj);  
                  String jsonStr 
          = jsonValue.render(false);
                  
          return jsonStr;
              }

              
              
          /**
               * 重載objectToJsonStr方法
               * 
          @param obj 需要轉換的JAVA對象
               * 
          @param format 是否格式化
               * 
          @return
               * 
          @throws MapperException
               
          */

              
          public static String objectToJsonStr(Object obj,boolean format) throws MapperException{
                  JSONValue jsonValue 
          = JSONMapper.toJSON(obj);  
                  String jsonStr 
          = jsonValue.render(format);
                  
          return jsonStr;
              }
              
              
              
          /**
               * JSON字符串轉換成JAVA對象
               * 
          @param jsonStr
               * 
          @param cla
               * 
          @return
               * 
          @throws MapperException
               * 
          @throws TokenStreamException
               * 
          @throws RecognitionException
               
          */

              @SuppressWarnings(
          "rawtypes""unchecked" })
              
          public static Object jsonStrToObject(String jsonStr,Class<?> cla) throws MapperException, TokenStreamException, RecognitionException{
                  Object obj 
          = null;
                  
          try{
                      JSONParser parser 
          = new JSONParser(new StringReader(jsonStr));    
                      JSONValue jsonValue 
          = parser.nextValue();              
                      
          if(jsonValue instanceof com.sdicons.json.model.JSONArray){
                          List list 
          = new ArrayList();
                          JSONArray jsonArray 
          = (JSONArray) jsonValue;
                          
          for(int i=0;i<jsonArray.size();i++){
                              JSONValue jsonObj 
          = jsonArray.get(i);
                              Object javaObj 
          = JSONMapper.toJava(jsonObj,cla); 
                              list.add(javaObj);
                          }

                          obj 
          = list;
                      }
          else if(jsonValue instanceof com.sdicons.json.model.JSONObject){
                          obj 
          = JSONMapper.toJava(jsonValue,cla); 
                      }
          else{
                          obj 
          = jsonValue;
                      }

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

                  
          return obj; 
              }

              
              
          /**
               * 將JAVA對象轉換成JSON字符串
               * 
          @param obj
               * 
          @return
               * 
          @throws IllegalArgumentException
               * 
          @throws IllegalAccessException
               
          */

              @SuppressWarnings(
          "rawtypes")
              
          public static String simpleObjectToJsonStr(Object obj,List<Class> claList) throws IllegalArgumentException, IllegalAccessException{
                  
          if(obj==null){
                      
          return "null";
                  }

                  String jsonStr 
          = "{";
                  Class
          <?> cla = obj.getClass();
                  Field fields[] 
          = cla.getDeclaredFields();
                  
          for (Field field : fields) {
                      field.setAccessible(
          true);
                      
          if(field.getType() == long.class){
                          jsonStr 
          += "\""+field.getName()+"\":"+field.getLong(obj)+",";
                      }
          else if(field.getType() == double.class){
                          jsonStr 
          += "\""+field.getName()+"\":"+field.getDouble(obj)+",";
                      }
          else if(field.getType() == float.class){
                          jsonStr 
          += "\""+field.getName()+"\":"+field.getFloat(obj)+",";
                      }
          else if(field.getType() == int.class){
                          jsonStr 
          += "\""+field.getName()+"\":"+field.getInt(obj)+",";
                      }
          else if(field.getType() == boolean.class){
                          jsonStr 
          += "\""+field.getName()+"\":"+field.getBoolean(obj)+",";
                      }
          else if(field.getType() == Integer.class||field.getType() == Boolean.class
                              
          ||field.getType() == Double.class||field.getType() == Float.class                    
                              
          ||field.getType() == Long.class){                
                          jsonStr 
          += "\""+field.getName()+"\":"+field.get(obj)+",";
                      }
          else if(field.getType() == String.class){
                          jsonStr 
          += "\""+field.getName()+"\":\""+field.get(obj)+"\",";
                      }
          else if(field.getType() == List.class){
                          String value 
          = simpleListToJsonStr((List<?>)field.get(obj),claList);
                          jsonStr 
          += "\""+field.getName()+"\":"+value+",";                
                      }
          else{        
                          
          if(claList!=null&&claList.size()!=0&&claList.contains(field.getType())){
                              String value 
          = simpleObjectToJsonStr(field.get(obj),claList);
                              jsonStr 
          += "\""+field.getName()+"\":"+value+",";                    
                          }
          else{
                              jsonStr 
          += "\""+field.getName()+"\":null,";
                          }

                      }

                  }

                  jsonStr 
          = jsonStr.substring(0,jsonStr.length()-1);
                  jsonStr 
          += "}";
                      
          return jsonStr;        
              }

              
              
          /**
               * 將JAVA的LIST轉換成JSON字符串
               * 
          @param list
               * 
          @return
               * 
          @throws IllegalArgumentException
               * 
          @throws IllegalAccessException
               
          */

              @SuppressWarnings(
          "rawtypes")
              
          public static String simpleListToJsonStr(List<?> list,List<Class> claList) throws IllegalArgumentException, IllegalAccessException{
                  
          if(list==null||list.size()==0){
                      
          return "[]";
                  }

                  String jsonStr 
          = "[";
                  
          for (Object object : list) {
                      jsonStr 
          += simpleObjectToJsonStr(object,claList)+",";
                  }

                  jsonStr 
          = jsonStr.substring(0,jsonStr.length()-1);
                  jsonStr 
          += "]";        
                  
          return jsonStr;
              }
              
              
              
          /**
               * 將JAVA的MAP轉換成JSON字符串,
               * 只轉換第一層數據
               * 
          @param map
               * 
          @return
               
          */

              
          public static String simpleMapToJsonStr(Map<?,?> map){
                  
          if(map==null||map.isEmpty()){
                      
          return "null";
                  }

                  String jsonStr 
          = "{";
                  Set
          <?> keySet = map.keySet();
                  
          for (Object key : keySet) {
                      jsonStr 
          += "\""+key+"\":\""+map.get(key)+"\",";        
                  }

                  jsonStr 
          = jsonStr.substring(0,jsonStr.length()-1);
                  jsonStr 
          += "}";
                  
          return jsonStr;
              }

          }


          文章詳細參考:http://blog.csdn.net/sjiang2142/article/details/6770672

          歡迎大家訪問我的個人網站 萌萌的IT人

          posted on 2014-07-22 15:14 一堣而安 閱讀(3928) 評論(0)  編輯  收藏 所屬分類: java

          導航

          統計

          常用鏈接

          留言簿(1)

          隨筆分類

          隨筆檔案

          收藏夾

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 贵州省| 潍坊市| 黄山市| 遂平县| 额济纳旗| 共和县| 汉中市| 溧水县| 尼玛县| 温州市| 唐河县| 扶风县| 北海市| 搜索| 始兴县| 东辽县| 句容市| 项城市| 梁河县| 华坪县| 满城县| 樟树市| 长海县| 肃宁县| 天全县| 定安县| 广宗县| 祥云县| 巩义市| 怀远县| 浮梁县| 潞城市| 海淀区| 改则县| 南乐县| 共和县| 罗城| 五大连池市| 仲巴县| 大姚县| 蓝田县|