package com.chauvet.utils.json; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.List; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.xml.XMLSerializer; import org.apache.commons.lang.StringUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class JsonUtils { private final static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); private static XMLSerializer xmlserializer = new XMLSerializer(); public static Gson getInstance(){ return gson; } /*** * List 轉為 JSON * @param list * @return */ public static <T> String list2Json(List<T> list) { if(null != list && list.size() > 0){ JSONArray jsonArray = JSONArray.fromObject(list); return jsonArray.toString(); } return ""; } /*** * JSON 轉換為 List * @param jsonStr * [{"age":12,"createTime":null,"id":"","name":"wxw","registerTime":null,"sex":1},{...}] * @param objectClass * @return */ @SuppressWarnings("unchecked") public static <T> List<T> json2List(String jsonStr, Class<T> objectClass){ if (StringUtils.isNotBlank(jsonStr)) { JSONArray jsonArray = JSONArray.fromObject(jsonStr); List<T> list = (List<T>) JSONArray.toCollection(jsonArray, objectClass); return list; } return null; } /*** * Object 轉為 JSON * @param object * @return */ public static String object2Json(Object object) { if(null != object){ JSONArray jsonArray = JSONArray.fromObject(object); return jsonArray.toString(); } return ""; } /*** * * JSON 轉 Object * * @param jsonStr * [{"age":12,"createTime":null,"id":"","name":"wxw","registerTime":null,"sex":1}] * @param objectClass * @return */ @SuppressWarnings("unchecked") public static <T> T json2Ojbect(String jsonStr, Class<T> objectClass){ if(null != jsonStr){ String leftStr = jsonStr.substring(0,2); String rightStr = jsonStr.substring(jsonStr.length()-2,jsonStr.length()); if(leftStr.equals("[{")){ jsonStr = jsonStr.substring(1,jsonStr.length()); } if(rightStr.equals("}]")){ jsonStr = jsonStr.substring(0,jsonStr.length()-1); } JSONObject jsonStu = JSONObject.fromObject(jsonStr); return (T) JSONObject.toBean(jsonStu,objectClass); } return null; } /*** * JsonArray 轉為 JSON * @param jsonArray * @return */ public static String jsonArrayToJSONString(JSONArray jsonArray) { if(null != jsonArray){ return jsonArray.toString(); } return ""; } /*** * JsonObject 轉為 JSON * @param jsonObject * @return */ public static String jsonObjectToJSONString(JSONObject jsonObject) { if(null != jsonObject){ return jsonObject.toString(); } return ""; } /*** * 將Object轉換為JsonObject * @param object * @return */ public static JSONObject object2JsonObject(Object object) { if(null != object){ return JSONObject.fromObject(object); } return null; } /*** * XML 轉為 JSON * @param xmlString * XML字符串 例如: * <?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> * @return * */ public static String xml2json(String xmlString){ if(StringUtils.isNotBlank(xmlString)){ try { return xmlserializer.read(xmlString).toString(); } catch (Exception e) { e.printStackTrace(); return null; } } return null; } /*** * JSON 轉為 XML * @param xmlString * XML字符串 例如: * [{'province':{'@name':'北京','item':['東城區','西城區','崇文區','宣武區','朝陽區','豐台區','石景山區','海淀區','門頭溝區','房山區','通州區','順義區','昌平區','大興區','懷柔區','平谷區','密雲縣','延慶縣']}}] * 或者: * {'province':{'@name':'北京','item':['東城區','西城區','崇文區','宣武區','朝陽區','豐台區','石景山區','海淀區','門頭溝區','房山區','通州區','順義區','昌平區','大興區','懷柔區','平谷區','密雲縣','延慶縣']}} * @return * */ public static String json2xml(String jsonStr){ if(StringUtils.isNotBlank(jsonStr)){ try { if(jsonStr.contains("[{") && jsonStr.contains("}]")){ JSONArray jobj = JSONArray.fromObject(jsonStr); return xmlserializer.write(jobj); } JSONObject jobj = JSONObject.fromObject(jsonStr); return xmlserializer.write(jobj); } catch (Exception e) { e.printStackTrace(); return null; } } return null; } /*** * XML/JSON 互轉 * * @param sourceFilePath * 要解析的文件路徑 * @param directFilePath * 生成文件存放的路徑 * @param flag * true:JSON 轉為 XML * false:XML轉為 JSON * @return */ public static String xml2JsonOrjson2Xml(String sourceFilePath,String directFilePath,boolean flag){ if(StringUtils.isBlank(sourceFilePath) || StringUtils.isBlank(directFilePath)){ return null; } FileInputStream in =null; BufferedReader br = null; FileWriter fw = null; String rs = null; try{ File jsonFile = new File(sourceFilePath); in = new FileInputStream(jsonFile); StringBuffer sbuf = new StringBuffer(); br = new BufferedReader(new InputStreamReader(in)); String temp =null; while((temp=br.readLine())!=null){ sbuf.append(temp); } if(flag){ rs = json2xml(sbuf.toString()); }else{ rs = xml2json(sbuf.toString()); } File test = new File(directFilePath); if(!test.exists()){ test.createNewFile(); } fw = new FileWriter(test); fw.write(rs); }catch (Exception e) { e.printStackTrace(); }finally{ try { fw.close(); br.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } } return rs; } public static void main(String[] args) { // System.out.println(jfxfTranspose("E:/qwe.json", "E:/qwe.xml", 1)); // System.out.println(json2xml("[{'province':{'@name':'北京','item':['東城區','西城區','崇文區','宣武區','朝陽區','豐台區','石景山區','海淀區','門頭溝區','房山區','通州區','順義區','昌平區','大興區','懷柔區','平谷區','密雲縣','延慶縣']}}]")); // 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>")); /*User u = new User(); u.setName("wxw"); u.setAge(12); u.setSex(1); System.out.println(object2JsonObject(u));*/ /*User u = new User(); u.setName("wxw"); u.setAge(12); u.setSex(1); System.out.println(object2Json(u));*/ /*User us = json2Ojbect(object2Json(u), User.class); System.out.println(us); */ /*List<User> list = new ArrayList<User>(); User u = new User(); u.setName("wxw"); u.setAge(12); u.setSex(1); list.add(u); u = new User(); u.setName("zmx"); u.setAge(12); u.setSex(0); list.add(u); u = new User(); u.setName("arnold"); u.setAge(12); u.setSex(1); list.add(u); String str = list2Json(list); System.out.println(str);*/ /*List<User> userList = converAnswerFormString(str, User.class); System.out.println(userList); */ } }