将JAVA对象转换成JSON字符串 .

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

猜你喜欢

转载自zgq456.iteye.com/blog/1927600