json:java对象与json字符串互转、java的list和map各自与json字符串的互转

来源:互联网 发布:英雄联盟关注软件 编辑:程序博客网 时间:2024/05/30 05:41
  1. import java.io.StringReader;  
  2. import java.lang.reflect.Field;  
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import java.util.Set;  
  7.   
  8. import antlr.RecognitionException;  
  9. import antlr.TokenStreamException;  
  10.   
  11. import com.sdicons.json.mapper.JSONMapper;  
  12. import com.sdicons.json.mapper.MapperException;  
  13. import com.sdicons.json.model.JSONArray;  
  14. import com.sdicons.json.model.JSONValue;  
  15. import com.sdicons.json.parser.JSONParser;  
  16.   
  17. public class JsonUtil {  
  18.   
  19.     /** 
  20.      * JAVA对象转换成JSON字符串 
  21.      * @param obj 
  22.      * @return 
  23.      * @throws MapperException 
  24.      */   
  25.     public static String objectToJsonStr(Object obj) throws MapperException{  
  26.         JSONValue jsonValue = JSONMapper.toJSON(obj);    
  27.         String jsonStr = jsonValue.render(false);  
  28.         return jsonStr;  
  29.     }  
  30.       
  31.     /** 
  32.      * 重载objectToJsonStr方法 
  33.      * @param obj 需要转换的JAVA对象 
  34.      * @param format 是否格式化 
  35.      * @return 
  36.      * @throws MapperException 
  37.      */  
  38.     public static String objectToJsonStr(Object obj,boolean format) throws MapperException{  
  39.         JSONValue jsonValue = JSONMapper.toJSON(obj);    
  40.         String jsonStr = jsonValue.render(format);  
  41.         return jsonStr;  
  42.     }     
  43.       
  44.     /** 
  45.      * JSON字符串转换成JAVA对象 
  46.      * @param jsonStr 
  47.      * @param cla 
  48.      * @return 
  49.      * @throws MapperException 
  50.      * @throws TokenStreamException 
  51.      * @throws RecognitionException 
  52.      */  
  53.     @SuppressWarnings({ "rawtypes""unchecked" })  
  54.     public static Object jsonStrToObject(String jsonStr,Class<?> cla) throws MapperException, TokenStreamException, RecognitionException{  
  55.         Object obj = null;  
  56.         try{  
  57.             JSONParser parser = new JSONParser(new StringReader(jsonStr));      
  58.             JSONValue jsonValue = parser.nextValue();             
  59.             if(jsonValue instanceof com.sdicons.json.model.JSONArray){  
  60.                 List list = new ArrayList();  
  61.                 JSONArray jsonArray = (JSONArray) jsonValue;  
  62.                 for(int i=0;i<jsonArray.size();i++){  
  63.                     JSONValue jsonObj = jsonArray.get(i);  
  64.                     Object javaObj = JSONMapper.toJava(jsonObj,cla);   
  65.                     list.add(javaObj);  
  66.                 }  
  67.                 obj = list;  
  68.             }else if(jsonValue instanceof com.sdicons.json.model.JSONObject){  
  69.                 obj = JSONMapper.toJava(jsonValue,cla);   
  70.             }else{  
  71.                 obj = jsonValue;  
  72.             }  
  73.         }catch(Exception e){  
  74.             e.printStackTrace();  
  75.         }  
  76.         return obj;   
  77.     }  
  78.       
  79.     /** 
  80.      * 将JAVA对象转换成JSON字符串 
  81.      * @param obj 
  82.      * @return 
  83.      * @throws IllegalArgumentException 
  84.      * @throws IllegalAccessException 
  85.      */  
  86.     @SuppressWarnings("rawtypes")  
  87.     public static String simpleObjectToJsonStr(Object obj,List<Class> claList) throws IllegalArgumentException, IllegalAccessException{  
  88.         if(obj==null){  
  89.             return "null";  
  90.         }  
  91.         String jsonStr = "{";  
  92.         Class<?> cla = obj.getClass();  
  93.         Field fields[] = cla.getDeclaredFields();  
  94.         for (Field field : fields) {  
  95.             field.setAccessible(true);  
  96.             if(field.getType() == long.class){  
  97.                 jsonStr += "\""+field.getName()+"\":"+field.getLong(obj)+",";  
  98.             }else if(field.getType() == double.class){  
  99.                 jsonStr += "\""+field.getName()+"\":"+field.getDouble(obj)+",";  
  100.             }else if(field.getType() == float.class){  
  101.                 jsonStr += "\""+field.getName()+"\":"+field.getFloat(obj)+",";  
  102.             }else if(field.getType() == int.class){  
  103.                 jsonStr += "\""+field.getName()+"\":"+field.getInt(obj)+",";  
  104.             }else if(field.getType() == boolean.class){  
  105.                 jsonStr += "\""+field.getName()+"\":"+field.getBoolean(obj)+",";  
  106.             }else if(field.getType() == Integer.class||field.getType() == Boolean.class  
  107.                     ||field.getType() == Double.class||field.getType() == Float.class                     
  108.                     ||field.getType() == Long.class){                 
  109.                 jsonStr += "\""+field.getName()+"\":"+field.get(obj)+",";  
  110.             }else if(field.getType() == String.class){  
  111.                 jsonStr += "\""+field.getName()+"\":\""+field.get(obj)+"\",";  
  112.             }else if(field.getType() == List.class){  
  113.                 String value = simpleListToJsonStr((List<?>)field.get(obj),claList);  
  114.                 jsonStr += "\""+field.getName()+"\":"+value+",";                  
  115.             }else{        
  116.                 if(claList!=null&&claList.size()!=0&&claList.contains(field.getType())){  
  117.                     String value = simpleObjectToJsonStr(field.get(obj),claList);  
  118.                     jsonStr += "\""+field.getName()+"\":"+value+",";                      
  119.                 }else{  
  120.                     jsonStr += "\""+field.getName()+"\":null,";  
  121.                 }  
  122.             }  
  123.         }  
  124.         jsonStr = jsonStr.substring(0,jsonStr.length()-1);  
  125.         jsonStr += "}";  
  126.             return jsonStr;       
  127.     }  
  128.       
  129.     /** 
  130.      * 将JAVA的LIST转换成JSON字符串 
  131.      * @param list 
  132.      * @return 
  133.      * @throws IllegalArgumentException 
  134.      * @throws IllegalAccessException 
  135.      */  
  136.     @SuppressWarnings("rawtypes")  
  137.     public static String simpleListToJsonStr(List<?> list,List<Class> claList) throws IllegalArgumentException, IllegalAccessException{  
  138.         if(list==null||list.size()==0){  
  139.             return "[]";  
  140.         }  
  141.         String jsonStr = "[";  
  142.         for (Object object : list) {  
  143.             jsonStr += simpleObjectToJsonStr(object,claList)+",";  
  144.         }  
  145.         jsonStr = jsonStr.substring(0,jsonStr.length()-1);  
  146.         jsonStr += "]";       
  147.         return jsonStr;  
  148.     }     
  149.       
  150.     /** 
  151.      * 将JAVA的MAP转换成JSON字符串, 
  152.      * 只转换第一层数据 
  153.      * @param map 
  154.      * @return 
  155.      */  
  156.     public static String simpleMapToJsonStr(Map<?,?> map){  
  157.         if(map==null||map.isEmpty()){  
  158.             return "null";  
  159.         }  
  160.         String jsonStr = "{";  
  161.         Set<?> keySet = map.keySet();  
  162.         for (Object key : keySet) {  
  163.             jsonStr += "\""+key+"\":\""+map.get(key)+"\",";       
  164.         }  
  165.         jsonStr = jsonStr.substring(0,jsonStr.length()-1);  
  166.         jsonStr += "}";  
  167.         return jsonStr;  
  168.     }  
  169. }  

注意:实际运行程序时需导入包jsontools-core-1.7.jar

原创粉丝点击