JSONUtil(JAVA对象/List与json互转,xml与json互转)

  1 package com.chauvet.utils.json;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileWriter;
  7 import java.io.InputStreamReader;
  8 import java.util.List;
  9 
 10 import net.sf.json.JSONArray;
 11 import net.sf.json.JSONObject;
 12 import net.sf.json.xml.XMLSerializer;
 13 
 14 import org.apache.commons.lang.StringUtils;
 15 
 16 import com.google.gson.Gson;
 17 import com.google.gson.GsonBuilder;
 18 
 19 
 20 public class JsonUtils {
 21     private final static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
 22     private static XMLSerializer xmlserializer = new XMLSerializer();
 23     
 24     public static Gson getInstance(){
 25         return gson;
 26     }
 27     
 28     /***
 29      * List 转为 JSON
 30      * @param list
 31      * @return
 32      */
 33     public static <T> String list2Json(List<T> list) {
 34         if(null != list && list.size() > 0){
 35             JSONArray jsonArray = JSONArray.fromObject(list);
 36             return jsonArray.toString();
 37         }
 38         return "";
 39     }
 40     
 41     
 42     /***
 43      * JSON 转换为 List
 44      * @param jsonStr
 45      *         [{"age":12,"createTime":null,"id":"","name":"wxw","registerTime":null,"sex":1},{...}]
 46      * @param objectClass
 47      * @return
 48      */
 49     @SuppressWarnings("unchecked")
 50     public static <T> List<T> json2List(String jsonStr, Class<T> objectClass){  
 51         if (StringUtils.isNotBlank(jsonStr)) {
 52             JSONArray jsonArray = JSONArray.fromObject(jsonStr);  
 53             List<T> list = (List<T>) JSONArray.toCollection(jsonArray, objectClass);  
 54             return list;  
 55         }
 56         return null;
 57     }  
 58     
 59     
 60     /***
 61      * Object 转为  JSON
 62      * @param object
 63      * @return
 64      */
 65     public static String object2Json(Object object) {
 66         if(null != object){
 67             JSONArray jsonArray = JSONArray.fromObject(object);
 68             return jsonArray.toString();
 69         }
 70         return "";
 71     }
 72     
 73     /***
 74      * 
 75      * JSON 转 Object
 76      * 
 77      * @param jsonStr
 78      *         [{"age":12,"createTime":null,"id":"","name":"wxw","registerTime":null,"sex":1}]
 79      * @param objectClass
 80      * @return
 81      */
 82     @SuppressWarnings("unchecked")
 83     public static <T> T json2Ojbect(String jsonStr,  Class<T> objectClass){
 84         if(null != jsonStr){
 85             String leftStr = jsonStr.substring(0,2);
 86             String rightStr = jsonStr.substring(jsonStr.length()-2,jsonStr.length());
 87             if(leftStr.equals("[{")){
 88                 jsonStr = jsonStr.substring(1,jsonStr.length());
 89             }
 90             if(rightStr.equals("}]")){
 91                 jsonStr = jsonStr.substring(0,jsonStr.length()-1);
 92             }
 93             JSONObject jsonStu = JSONObject.fromObject(jsonStr); 
 94             return (T) JSONObject.toBean(jsonStu,objectClass);
 95         }
 96         return null;
 97     }
 98 
 99     /***
100      * JsonArray 转为 JSON
101      * @param jsonArray
102      * @return
103      */
104     public static String jsonArrayToJSONString(JSONArray jsonArray) {
105         if(null != jsonArray){
106             return jsonArray.toString();
107         }
108         return "";
109     }
110 
111     /***
112      * JsonObject 转为  JSON
113      * @param jsonObject
114      * @return
115      */
116     public static String jsonObjectToJSONString(JSONObject jsonObject) {
117         if(null != jsonObject){
118             return jsonObject.toString();
119         }
120         return "";
121     } 
122     
123     /***
124      * 将Object转换为JsonObject
125      * @param object
126      * @return
127      */
128     public static JSONObject object2JsonObject(Object object) {
129         if(null != object){
130             return JSONObject.fromObject(object);
131         }
132         return null;
133     }
134 
135     
136     /***
137      * XML 转为 JSON
138      * @param xmlString
139      *             XML字符串  例如:
140      *                     <?xml version='1.0' encoding='utf-8'?><cities><province name='北京'><item>东城区</item><item>西城区</item><item>崇文区</item><item>宣武区</item><item>朝阳区</item><item>丰台区</item><item>石景山区</item><item>海淀区</item><item>门头沟区</item><item>房山区</item><item>通州区</item><item>顺义区</item><item>昌平区</item><item>大兴区</item><item>怀柔区</item><item>平谷区</item><item>密云县</item><item>延庆县</item></province></cities>
141      * @return
142      * 
143      */
144     public static String xml2json(String xmlString){
145         if(StringUtils.isNotBlank(xmlString)){
146             try {
147                 return xmlserializer.read(xmlString).toString();
148             } catch (Exception e) {
149                 e.printStackTrace();
150                 return null;
151             }
152         }
153         return null;
154     }
155 
156     /***
157      * JSON 转为      XML
158      * @param xmlString
159      *             XML字符串  例如:
160      *                     [{'province':{'@name':'北京','item':['东城区','西城区','崇文区','宣武区','朝阳区','丰台区','石景山区','海淀区','门头沟区','房山区','通州区','顺义区','昌平区','大兴区','怀柔区','平谷区','密云县','延庆县']}}]
161      *                  或者:
162      *                  {'province':{'@name':'北京','item':['东城区','西城区','崇文区','宣武区','朝阳区','丰台区','石景山区','海淀区','门头沟区','房山区','通州区','顺义区','昌平区','大兴区','怀柔区','平谷区','密云县','延庆县']}}
163      * @return
164      * 
165      */
166     public static String json2xml(String jsonStr){
167         if(StringUtils.isNotBlank(jsonStr)){
168             try {
169                 if(jsonStr.contains("[{") && jsonStr.contains("}]")){
170                     JSONArray jobj = JSONArray.fromObject(jsonStr);
171                     return xmlserializer.write(jobj);
172                 }
173                 JSONObject jobj = JSONObject.fromObject(jsonStr);
174                 return xmlserializer.write(jobj);
175             } catch (Exception e) {
176                 e.printStackTrace();
177                 return null;
178             }
179         }
180         return null;
181     }
182     
183     
184     /***
185      * XML/JSON 互转
186      * 
187      * @param sourceFilePath
188      *                 要解析的文件路径
189      * @param directFilePath
190      *              生成文件存放的路径
191      * @param flag
192      *             true:JSON 转为 XML
193      *             false:XML转为 JSON
194      * @return
195      */
196     public static String xml2JsonOrjson2Xml(String sourceFilePath,String directFilePath,boolean flag){
197         if(StringUtils.isBlank(sourceFilePath) || StringUtils.isBlank(directFilePath)){
198             return null;
199         }
200         FileInputStream in =null;
201         BufferedReader br = null; 
202         FileWriter fw = null;
203         String rs = null;
204         try{
205             File jsonFile = new File(sourceFilePath);
206             in = new FileInputStream(jsonFile); 
207             StringBuffer sbuf = new StringBuffer();
208             br = new BufferedReader(new InputStreamReader(in));
209             String temp =null;
210 
211             while((temp=br.readLine())!=null){
212                 sbuf.append(temp);
213             }
214             if(flag){
215                 rs  = json2xml(sbuf.toString());
216             }else{
217                 rs  = xml2json(sbuf.toString());
218             }
219             File test = new File(directFilePath);
220             if(!test.exists()){
221                 test.createNewFile();
222             }
223             fw = new FileWriter(test);
224             fw.write(rs);
225          }catch (Exception e) {
226              e.printStackTrace();
227         }finally{
228             try {
229                 fw.close();
230                 br.close();
231                 in.close();
232             } catch (Exception e) {
233                 e.printStackTrace();
234             }
235         }
236         return rs;
237     }
238     
239     
240     public static void main(String[] args) {
241         
242 //        System.out.println(jfxfTranspose("E:/qwe.json", "E:/qwe.xml", 1));
243         
244 //        System.out.println(json2xml("[{'province':{'@name':'北京','item':['东城区','西城区','崇文区','宣武区','朝阳区','丰台区','石景山区','海淀区','门头沟区','房山区','通州区','顺义区','昌平区','大兴区','怀柔区','平谷区','密云县','延庆县']}}]"));
245 //        System.out.println(xml2json("<?xml version='1.0' encoding='utf-8'?><cities><province name='北京'><item>东城区</item><item>西城区</item><item>崇文区</item><item>宣武区</item><item>朝阳区</item><item>丰台区</item><item>石景山区</item><item>海淀区</item><item>门头沟区</item><item>房山区</item><item>通州区</item><item>顺义区</item><item>昌平区</item><item>大兴区</item><item>怀柔区</item><item>平谷区</item><item>密云县</item><item>延庆县</item></province></cities>"));
246         
247         /*User u = new User();
248         u.setName("wxw");
249         u.setAge(12);
250         u.setSex(1);
251         System.out.println(object2JsonObject(u));*/
252         
253         /*User u = new User();
254         u.setName("wxw");
255         u.setAge(12);
256         u.setSex(1);
257         System.out.println(object2Json(u));*/
258 
259         /*User us = json2Ojbect(object2Json(u), User.class);
260         System.out.println(us);
261         */
262         
263         /*List<User> list = new ArrayList<User>();
264         User u = new User();
265         u.setName("wxw");
266         u.setAge(12);
267         u.setSex(1);
268         list.add(u);
269         u = new User();
270         u.setName("zmx");
271         u.setAge(12);
272         u.setSex(0);
273         list.add(u);
274         u = new User();
275         u.setName("arnold");
276         u.setAge(12);
277         u.setSex(1);
278         list.add(u);
279         String str = list2Json(list);
280         System.out.println(str);*/
281         
282         /*List<User> userList = converAnswerFormString(str, User.class);
283         System.out.println(userList);
284         */
285          
286     }
287 }

 

posted @ 2017-11-10 22:16  chenxiangxiang  阅读(6310)  评论(0编辑  收藏  举报